* Procedures, a built-in, first-class type of Scheme ** lambda makes procedures ---------- ((lambda (x) x) 'y) ; Value: Y ((lambda (x) (car x)) '(a b c)) ; Value: A ------- ---------- ((lambda (x y) 0) 'a 'b) ; Value: 0 ((lambda () 5)) ; no arguments ; Value: 5 ---------- ** Procedures first-class in LISP: *** examples --------------- (lambda (x) x) ; identity function ; Value: #[COMPOUND-PROCEDURE #x1A0418] (define id (lambda (x) x)) (id 1) ; Value: 1 ((lambda (y) y) 3) ; Value: 3 (define one 1) (define inc (lambda (x) (+ one x))) (inc 2) ; Value: 3 (set! one 2) ; mutation of global environment! (inc 2) ; Value: 4 ; closes over bindings, not values! ------------------- *** environment model **Quiz on the above: ---------- Consider the following definitions: (define (compose f g) (lambda (x) (f (g x)))) (define (curry f) (lambda (x) (lambda (y) (f x y)))) What are the values of the following expressions: 1. ((compose car cdr) '(a b c)) 2. ((compose car (compose cdr cdr)) '(a b c)) 3. (((curry +) 1) 2) ---------- *** functionals ------------------- ;; combinators: (define B (curry compose)) (define (W f) (lambda (x) ((f x) x))) (define twice (W B)) (define I (lambda (x) x)) (define (K c) (lambda (x) c)) (define (S f g) (lambda (x) (f x (g x)))) (define CS (curry S)) ;; applicative order Y combinator: (define (Y M) ((lambda (future) (M (lambda (arg) ((future future) arg)))) (lambda (future) (M (lambda (arg) ((future future) arg)))))) ------------------- * Lambda the Ultimate ** the Y-combinator can be used to make recursive functions ------------- (define oh-no (Y (lambda (recurse) (lambda (x) (recurse x))))) (define length (Y (lambda (recurse) (lambda (l) (cond ((null? l) 0) (else (+ 1 (recurse (cdr l))))))))) ------------- ** closures can be used to delay evaluation ------------- (define (if-closures e1 c2 c3) (if e1 (c2) (c3))) (if-closures #t (lambda () (+ 3 4)) (lambda () (oh-no #t))) ; Value: 7 ------------- * Analysis of the Functional Paradigm and Scheme ** Scheme and LISP ** Applicative programming ** Functional programming