Next. Tail Recursion: Factorial. How does it execute? Tail recursion. Tail recursive factorial. Tail recursive factorial.

Similar documents
Factorial. Next. Factorial. How does it execute? Tail recursion. How does it execute? More on recursion. Higher-order functions

Today. Recap from last Week. Factorial. Factorial. How does it execute? How does it execute? More on recursion. Higher-order functions

max function Next concat function max function What s the pattern? concat function More on recursion Higher-order functions

Today s Plan. Programming Languages. Example : Factorial. Recursion. CSE 130 : Spring Lecture 6: Higher-Order Functions

Programming Languages. Tail Recursion. CSE 130: Winter Lecture 8: NOT TR. last thing function does is a recursive call

Recap: Functions as first-class values

Write: evens. evens [] ====> [] evens [1;2;3;4] ====> [2;4]

Recursion. Q: What does this evaluate to? Q: What does this evaluate to? CSE 130 : Programming Languages. Higher-Order Functions

News. CSE 130: Programming Languages. Environments & Closures. Functions are first-class values. Recap: Functions as first-class values

CSE 130 [Winter 2014] Programming Languages

CMSC 330: Organization of Programming Languages. OCaml Higher Order Functions

CMSC 330: Organization of Programming Languages. OCaml Higher Order Functions

Functions Over Lists. Programming Languages and Compilers (CS 421) Structural Recursion. Functions Over Lists. Structural Recursion : List Example

CMSC 330: Organization of Programming Languages. OCaml Higher Order Functions

CSci 4223 Principles of Programming Languages

CMSC 330, Fall 2013, Practice Problems 3

CS Lecture 6: Map and Fold. Prof. Clarkson Spring Today s music: Selections from the soundtrack to 2001: A Space Odyssey

Begin at the beginning

CMSC 330, Fall 2013, Practice Problem 3 Solutions

# true;; - : bool = true. # false;; - : bool = false 9/10/ // = {s (5, "hi", 3.2), c 4, a 1, b 5} 9/10/2017 4

Functional Programming. Pure Functional Programming

Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Booleans and Short-Circuit Evaluation. Tuples as Values.

CS Lecture 6: Map and Fold. Prof. Clarkson Fall Today s music: Selections from the soundtrack to 2001: A Space Odyssey

Map and Fold. Prof. Clarkson Fall Today s music: Selections from the soundtrack to 2001: A Space Odyssey

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

Tail Recursion: Factorial. Begin at the beginning. How does it execute? Tail recursion. Tail recursive factorial. Tail recursive factorial

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

OCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type.

FUNCTIONAL PROGRAMMING

Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example

CSci 4223 Principles of Programming Languages

CS 312, Fall Exam 1

Programming Languages and Compilers (CS 421)

Plan (next 4 weeks) 1. Fast forward. 2. Rewind. 3. Slow motion. Rapid introduction to what s in OCaml. Go over the pieces individually

A brief tour of history

COP-5555 PROGRAMMING LANGUAGEPRINCIPLES NOTES ON RPAL

Monday Feb 16, 5pm. solve these equalities. Midterm Thursday Feb 12. covers only ocaml part of the course, assignments 1 through 3.

CSE341 Section 3. Standard-Library Docs, First-Class Functions, & More

CS 321 Programming Languages

15-451/651: Design & Analysis of Algorithms November 20, 2018 Lecture #23: Closest Pairs last changed: November 13, 2018

COSE212: Programming Languages. Lecture 4 Recursive and Higher-Order Programming

INF121: Functional Algorithmic and Programming

15-451/651: Design & Analysis of Algorithms April 18, 2016 Lecture #25 Closest Pairs last changed: April 18, 2016

OCaml. History, Variants. ML s holy trinity. Interacting with ML. Base type: Integers. Base type: Strings. *Notes from Sorin Lerner at UCSD*

Back to OCaml. Summary of polymorphism. Example 1. Type inference. Example 2. Example 2. Subtype. Polymorphic types allow us to reuse code.

Introduction to OCaml

News. Programming Languages. Complex types: Lists. Recap: ML s Holy Trinity. CSE 130: Spring 2012

Playing with Fun. Walter Cazzola. Playing with Fun currying partial evaluation map&reduce iteration var args. References.

Call-by-name evaluation

Redefinition of an identifier is OK, but this is redefinition not assignment; Thus

Recap from last time. Programming Languages. CSE 130 : Fall Lecture 3: Data Types. Put it together: a filter function

Forward Recursion. Programming Languages and Compilers (CS 421) Mapping Recursion. Forward Recursion: Examples. Folding Recursion.

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1

Programming Languages

Forward recursion. CS 321 Programming Languages. Functions calls and the stack. Functions calls and the stack

7.3.3 A Language With Nested Procedure Declarations

CMSC330 Fall 2016 Midterm #1 2:00pm/3:30pm

A Crash Course on Standard ML

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

LECTURE 16. Functional Programming

Variables and Bindings

CSCI 2041: First Class Functions

CSCI-GA Scripting Languages

Programming Languages

Currying fun f x y = expression;

F28PL1 Programming Languages. Lecture 14: Standard ML 4

So what does studying PL buy me?

Lecture 19: Functions, Types and Data Structures in Haskell

CSE 341 Lecture 5. efficiency issues; tail recursion; print Ullman ; 4.1. slides created by Marty Stepp

Any questions. Say hello to OCaml. Say hello to OCaml. Why readability matters. History, Variants. Plan (next 4 weeks)

Functional Programming. Pure Functional Programming

Programming Languages

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

CMSC330 Spring 2014 Midterm 2 Solutions

CS422 - Programming Language Design

CS1 Recitation. Week 2

Programming Languages and Techniques (CIS120)

Programming Languages

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

CS115 - Module 9 - filter, map, and friends

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

CMSC330 Fall 2014 Midterm 2 Solutions

Programming Languages

Lists. Michael P. Fourman. February 2, 2010

Gain familiarity and practice with folding and mapping. The following supplementary materials may be helpful in completing this assignment:

An introduction introduction to functional functional programming programming using usin Haskell

Homework 5. Notes. Turn-In Instructions. Reading. Problems. Handout 19 CSCI 334: Spring (Required) Read Mitchell, Chapters 6 and 7.

15 212: Principles of Programming. Some Notes on Continuations

1 Announcements. 2 Scan Implementation Recap. Recitation 4 Scan, Reduction, MapCollectReduce

Functional Programming in Haskell Part I : Basics

Final Exam CSCI 1101 Computer Science I KEY. Wednesday December 16, 2015 Instructor Muller Boston College. Fall 2015

Introduction to Functional Programming and Haskell. Aden Seaman

Programming Languages

Lecture 10: Recursion vs Iteration

CMSC 330: Organization of Programming Languages. Closures (Implementing Higher Order Functions)

Informatics 1 Functional Programming Lecture 7. Map, filter, fold. Don Sannella University of Edinburgh

F# - LISTS. In this method, you just specify a semicolon-delimited sequence of values in square brackets. For example

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

Transcription:

Next Tail Recursion: Factorial More on recursion Higher-order functions takg and returng functions Along the way, will see map and fold let rec fact n = if n<=0 then 1 else n * fact (n-1);; 1 2 How does it execute? let rec fact n = if n<=0 then 1 else n * fact (n-1);; fac 3;; Tail recursion Tail recursion: recursion where all recursive calls are immediately followed by a return other words: not allowed to do anythg between recursive call and return 3 4 Tail recursive factorial Tail recursive factorial let fact x = let fact x = let rec helper x curr = if x <= 0 then curr else helper (x - 1) (x * curr) helper x 1;; 5 6 1

How does it execute? Tail recursion let fact x = let rec helper x curr = if x <= 0 then curr else helper (x - 1) (x * curr) helper x 1;; Tail recursion: for each recursive call, the value of the recursive call is immediately returned other words: not allowed to do anythg between recursive call and return fact 3;; Why do we care about tail recursion? it turns out that tail recursion can be optimized to a simple loop 7 8 Compiler can optimize! Tail recursion summary let fact x = let rec helper x curr = if x <= 0 fact(x) { curr := 1; while (1) { if (x <= 0) Tail recursive calls can be optimized as a jump then curr else helper (x - 1) (x * curr) } then { return curr } else { x := x 1; curr := (x * curr) } Part of the language specification of some languages (ie: you can count on the compiler to optimize tail recursive calls) helper x 1;; recursion! Loop! 9 10 max function max function let max x y = if x < y then y else x;; let max x y = if x < y then y else x;; (* return max element of list l *) let list_max l = 11 (* return max element of list l *) let list_max l = h::t -> helper (max curr h) t helper 0 l;; 12 2

concat function concat function (* concatenate all strgs a list *) let concat l = (* concatenate all strgs a list *) let concat l = h::t -> helper (curr ^ h) t helper "" l;; 13 14 What s the pattern? fold, the general helper func! let list_max l = h::t -> helper (max h curr) t helper 0 l;; (* to help us see the pattern: *) let list_max l = h::t -> helper (max h curr) t helper 0 l;; let concat l = h::t -> helper (curr ^ h) t helper "" l;; 15 (* fold, the coolest function there is! *) let rec fold f curr l = 16 fold fold (* fold, the coolest function there is! *) let rec fold f curr l = h::t -> fold f (f curr h) t;; (* fold, the coolest function there is! *) let rec fold f curr l = h::t -> fold f (f curr h) t;; 17 18 3

Examples of fold Examples of fold let list_max = let list_max = fold max 0;; let concat = let concat = fold (^) "";; let multiplier = let multiplier = fold (*) 1;; 19 20 Examples of fold Examples of fold let fact n = multiplier (terval 1 n);; let cons x y = y::x;; let f = fold cons [];; (* same as: let f l = fold cons [] l *) Notice how all the recursion is buried side two functions: terval and fold! 21 22 Examples of fold More recursion: terval let cons x y = y::x;; let f = fold cons [];; (* same as: let f l = fold cons [] l *) (* return a list that contas the tegers i through j clusive *) let rec terval i j = 23 24 4

terval terval function with it fn (* return a list that contas the tegers i through j clusive *) let rec terval i j = if i > j then [] else i::(terval (i+1) j);; (* return a list that contas the elements f(i), f(i+1),... f(j) *) let rec terval_it i j f = 25 26 terval function with it fn terval function aga (* return a list that contas the elements f(i), f(i+1),... f(j) *) let rec terval_it i j f = if i > j then [] else (f i)::(terval_it (i+1) j f);; (* our regular terval function terms of the one with the it function *) let rec terval i j = 27 28 terval function aga Interval function yet aga! (* our regular terval function terms of the one with the it function *) let rec terval i j = terval_it i j (fun x -> x);; (* let's change the order of parameters... *) let rec terval_it f i j = if i > j then [] else (f i)::(terval_it f (i+1) j);; (* now can use curryg to get terval function! *) let terval = terval_it (fun x -> x);; 29 30 5

Function Curryg Function Curryg vs tuples In general, these two are equivalent: let f = fun x1 -> -> fun xn -> e Tuple version: fn defition let f (x1,,xn) = e fn call f (x1,,xn) let f x1 xn = e Multiple argument functions by returng a function that takes the next argument Named after a person (Haskell Curry) Curried version: fn defition let f x1 xn = e fn call f x1 xn 31 32 Function Curryg vs tuples map Consider the followg: let lt x y = x < y; (* return the list contag f(e) for each element e of l *) let rec map f l = Could have done: let lt (x,y) = x<y; But then no testers possible In general: Curryg allows you to set just the first n params (where n smaller than the total number of params) 33 34 map map (* return the list contag f(e) for each element e of l *) let rec map f l = [] -> [] h::t -> (f h)::(map f t);; let cr x = x+1;; let map_cr = map cr;; map_cr (terval (-10) 10);; 35 36 6

composg functions (f o g) (x) = f(g(x)) (* return a function that given an argument x applies f2 to x and then applies f1 to the result*) let compose f1 f2 = composg functions (f o g) (x) = f(g(x)) (* return a function that given an argument x applies f2 to x and then applies f1 to the result*) let compose f1 f2 = fun x -> (f1 (f2 x));; (* another way of writg it *) let compose f1 f2 x = f1 (f2 x);; 37 38 Higher-order functions! Higher-order functions! let map_cr_2 = compose map_cr map_cr;; map_cr_2 (terval (-10) 10);; let map_cr_3 = compose map_cr map_cr_2;; map_cr_3 (terval (-10) 10);; let map_cr_3_pos = compose pos_filer map_cr_3;; map_cr_3_pos (terval (-10) 10);; (compose map_cr_3 pos_filer) (terval (-10) 10);; let map_cr_2 = compose map_cr map_cr;; map_cr_2 (terval (-10) 10);; let map_cr_3 = compose map_cr map_cr_2;; map_cr_3 (terval (-10) 10);; let map_cr_3_pos = compose pos_filer map_cr_3;; map_cr_3_pos (terval (-10) 10);; (compose map_cr_3 pos_filer) (terval (-10) 10);; 39 Instead of manipulatg lists, we are manipulatg the list manipulators! 40 Exercise 1 let rec filter f l = [] -> [] h::t -> let t = filter f t if f h then h::t else t Exercise 1 val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a let partition f l = let neg f x = not (f x) let partition f l = (filter f l, filter (neg f) l) This implementation is not ideal, sce it unnecessarily processes the list twice. Rewrite partition so that it is a sgle call to fold_left, so the put list is processed only once. Recall: val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a 41 42 7

Exercise 1 Solution val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a let partition f l = let fold_fn (pass,passnot) x = if f x then (pass@[x], passnot) else (pass, passnot@[x]) List.fold_left fold_fn ([],[]) l;; Exercise 2 val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a val map : ('a -> 'b) -> 'a list -> 'b list Implement map usg fold: let map f l = 43 44 Exercise 2 Solution val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a val map : ('a -> 'b) -> 'a list -> 'b list Benefits of higher-order functions Identify common computation patterns Implement map usg fold: let map f l = List.fold_left (fun acc x -> acc@[f x]) [] l Iterate a function over a set, list, tree Accumulate some value over a collection Pull out (factor) common code: Computation Patterns Re-use many different situations 45 46 Funcs takg/returng funcs Higher-order funcs enable modular code Each part only needs local formation Data Structure Client Uses list Uses meta-functions: map,fold,filter Data Structure Library list Provides meta-functions: map,fold,filter Different way of thkg Free your md -Morpheus Different way of thkg about computation Manipulate the manipulators With locally-dependent funs to traverse, accumulate over (lt h), square etc. lists, trees etc. Without requirg Implement. Meta-functions don t need client details of data structure fo 47 48 8