lecture06

# lecture06 - Today COMPUTER SCIENCE 51 Spring 2009...

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

2/20/2009 1 COMPUTER SCIENCE 51 Spring 2009 cs51.seas.harvard.edu Prof. Greg Morrisett Prof. Ramin Zabih Today Higher-order functions lambda expressions passing lambdas to functions returning new lambda from functions Encoding features with lambda let declarations contracts pretty-printers Lambda Expressions When you write a function defn: ( define (inc x) (+ 1 x)) This is short-hand for: ( define inc ( lambda (x) (+ 1 x)) To save space, I will write: ( define inc ( λ (x) (+ 1 x)) Lambda’s Lambda expressions are anonymous functions: ( λ (x) (* x x)) The square function. It doesn’t need a name any more than we need to define 3 to be three or z . Lambda expressions are values, just like numbers, strings, etc. we can pass a lambda to a function. we can return a lambda from a function. we can place a lambda in a list. Let’s see why this is useful. .. Factoring Consider the following two functions: ( define (sum x) ( if (empty? x) 0 (+ (car x) (sum (cdr x))))) ( define (prod x) ( if (empty? x) 1 (* (car x) (prod (cdr x))))) Factoring ( define (foldr f u x) ( if (empty? x) u (f (car x) (foldr f u (cdr x))))) ( define (sum x) (foldr + 0 x)) ( define (prod x) (foldr * 1 x)) ( define (flatten x) (foldr append empty x)) ( define (mystery x) (foldr cons empty x))

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

View Full Document
2/20/2009 2 How to think of foldr • A list value looks like this: (cons v1 (cons v2 (. .. (cons vn empty). ..))) • A call to foldr with function f and value u replaces all of the cons’s with f and empty with u: (f v1 (f v2 (. .. (f vn u). ..))) For Example: (foldr + 0 (list 1 2 3 4)) = (foldr + 0 (cons 1 (cons 2 (cons 3 (cons 4 empty) ... )= (+ 1 (+ 2 (+ 3 (+ 4 0)))) = 10 Another Example (foldr * 1 (list 1 2 3 4)) = (foldr * 1 (cons 1 (cons 2 (cons 3 (cons 4 empty) ... )= (* 1 (* 2 (* 3 (* 4 1)))) = 24 A Slightly Different fold ( define (foldl f u x) ( if (empty? x) u (foldl f (f (car x) u) (cdr x)))) ( define (sum2 x) (foldl + 0 x)) ( define (prod2 x) (foldl * 1 x)) ( define (append2 x) (foldl append empty x)) How to think of foldl • Given a list x : (cons v1 (cons v2 (. .. (cons vn empty).
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 07/26/2009 for the course COMPUTERSC CS51 taught by Professor Gregmorrisett during the Spring '09 term at Harvard.

### Page1 / 7

lecture06 - Today COMPUTER SCIENCE 51 Spring 2009...

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

View Full Document
Ask a homework question - tutors are online