(define (swap f) (lambda (a b) (f b a))) (define (compose f g) ;; assume procedure of 1 argument (lambda (x) (f (g x)))) (define (double x) (* 2 x)) (define (square x) (* x x)) (define (cube x) (expt x 3)) (define f^3/2 (compose cube sqrt)) (define (f^3/2-v2 x) ((compose cube sqrt) x)) ;; repeated composition (define fourth (compose square square)) (define eighth (compose square (compose square square))) (define (repeat proc n) ;; repeat returns a procedure! ;; base case: what happens if no repeats? (if (= n 0) (lambda (x) x) (compose proc (repeat proc (- n 1))))) (define fourth-v2 (repeat square 2)) (define eighth-v2 (repeat square 3)) ;; iterative repeat: created iteratively, runs recursively (define (repeat-iter proc n) (define (iter-help ans n) (if (= n 0) ans (iter-help ;; "add" proc to ans using compose (compose proc ans) (- n 1)))) (iter-help (lambda (x) x) n)) (define fourth-v3 (repeat-iter square 2)) ;; really iterative: functions runs iteratively (define (repeat-totally-iter proc n) (lambda (x) (define (iter-help ans n) (if (= n 0) ans (iter-help (proc ans) (- n 1)))) (iter-help x n))) (define fourth-v4 (repeat-totally-iter square 2)) ;; another version of repeat (define (repeat-v2 f n) (cond ((= n 0) (lambda (x) x)) ((odd? n) (compose f (repeat-v2 f (- n 1)))) (else (repeat-v2 (compose f f) (/ n 2))))) ;; (mul a b): multiplication as repeated addition ;; how to use compose and a proc of one argument? (lambda (x) (+ x a)) and do it b times (repeat) (define (mul a b) ;; return a number, not a procedure! ((repeat (lambda (x) (+ x a)) b) 0)) ;; 0 is the additive identity ;; (define (mulv2 a b) ;; could do error checking for a and b negative ;; if a is negative, end up subtracting ;; can use absolute value ;; ...) ;; (my-exp a b): exponentiation as repeated addition (define (my-exp a b) ((repeat (lambda (x) (* x a)) b) 1))