[3/8/99] =============================================================================== * Talk more on procedures as arguments, and higher-order procedures (procedures as return values). A short & simple example: -------------------- (define (compose f g) (lambda (x) (f (g x)))) -------------------- What are the values of: -------------------- compose (compose sin cos) ((compose sin cos) 1) ((compose (compose sin cos) square) 1) -------------------- Yet another example: -------------------- (define (double f) (lambda (x) (f (f x)))) (define (add1 x) (+ x 1)) -------------------- Evaluate: -------------------- (((double double) add1) 2) ((double (double add1)) 2) -------------------- And note that double can be simply written as: -------------------- (define (double f) (compose f f)) -------------------- Another cute H.O. example: Yet another example: -------------------- (define (bin-currify f) (lambda (x) (lambda (y) (f x y)))) -------------------- Show examples. =============================================================================== * A more useful example for using higher order functions and generalization: We already saw the deriv function that got a number x, and a function f, and returns the estimated derivation of the f at point x (assume dx is now a global value): -------------------- (define (deriv f x) (/ (- (f (+ x dx)) (f x)) dx)) -------------------- This can be more elegant if the deriv function will get only f, returning its derivative as a value. Here is how this is done: -------------------- (define (deriv f) (lambda (x) (/ (- (f (+ x dx)) (f x)) dx))) -------------------- Or equivalently: -------------------- (define deriv (bin-currify f)) -------------------- This simple "Currification" got as an actual derivative - a function d such that: d(f) = f' =============================================================================== * A sophisticated example: -------------------- (define (repeated f n) (lambda (x) (if (= n 0) x ((repeated f (- n 1)) (f x))))) -------------------- this can be written in many alternate ways, here's one: -------------------- (define (identity x) x) (define (repeated f n) (if (zero? n) identity (lambda (x) ((repeated f (- n 1)) (f n))))) -------------------- and here is a tail-recursive version: -------------------- (define (repeated f n) (letrec ((iter (lambda (n f-acc) (if (zero? n) f-acc (iter (- n 1) (lambda (x) (f (f-acc x)))))))) (iter n identity))) -------------------- ===============================================================================