{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

lecture-7

# lecture-7 - Admin stuff PA 3 due Sunday 5pm Midterm Tuesday...

This preview shows pages 1–3. Sign up to view the full content.

1 Admin stuff • PA 3 due Sunday 5pm • Midterm Tuesday Oct 26 covers all of Ocaml, but only PA1-PA3 • PA 4 due Friday Oct 29 5pm Interpreter in Ocaml + parsing start early 1 2 Recap: max function let max x y = if x < y then y else x;; (* return max element of list l *) let list_max l = let rec helper curr l = match l with [] -> curr | h::t -> helper (max h curr) t in helper 0 l;; 3 Recap: concat function (* concatenate all strings in a list *) let concat l = let rec helper curr l = match l with [] -> curr | h::t -> helper (curr ^ h) t in helper "" l;; 4 What’s the pattern? let list_max l = let rec helper curr l = match l with [] -> curr | h::t -> helper (max h curr) t in helper 0 l;; let concat l = let rec helper curr l = match l with [] -> curr | h::t -> helper (curr ^ h) t in helper "" l;; 5 fold (* fold, the coolest function there is! *) let rec fold f curr l = (* to help us see the pattern: *) let list_max l = let rec helper curr l = match l with [] -> curr | h::t -> helper (max h curr) t in helper 0 l;; 6 fold (* fold, the coolest function there is! *) let rec fold f curr l = match l with [] -> curr | h::t -> fold f (f h curr) t;;

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2 7 Examples of fold let concat = fold (^) "";; let multiplier = fold (*) 1;; let list_max = fold max 0;; 8 Examples of fold let fact n = multiplier (interval 1 n);; Notice how all the recursion is buried inside two functions: interval and fold! 9 Examples of fold let cons x y = x::y;; let f = fold cons [];; (* same as: let f l = fold cons [] l *) 10 Examples of fold let cons x y = x::y;; let f = fold cons [];; (* same as: let f l = fold cons [] l *) Why are map/fold important? 11 12 Benefits of higher-order functions Identify common computation “patterns” Iterate a function over a set, list , tree … Accumulate some value over a collection
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 6

lecture-7 - Admin stuff PA 3 due Sunday 5pm Midterm Tuesday...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online