; The following definition of a recursive ; function in the binding list of a let ; expression DOES NOT WORK. Why not? ; We need to use a letrec to define a ; recursively defined proc in a let (let ((sum (lambda (ls) (if (null? ls) 0 (+ (car ls) (sum (cdr ls))))))) (sum '(1 2 3 4 5))) ; letrec is really useful when defining mutally recursive procedures (letrec ((even? (lambda (x) (or (= x 0) (odd? (- x 1))))) (odd? (lambda (x) (and (not (= x 0)) (even? (- x 1)))))) (list (even? 20) (odd? 20))) ; letrec is also useful for defining lists of procedures as an "object" ; (record of possibly mutually recursive methods) together with a ; "dispatcher" function that can be used to select a procedure and apply ; a list of arguments to it. (define object (letrec ; locally scoped "private" procedurs ((add (lambda (x y) (+ x y))) (sub (lambda (x y) (- x y))) (mul (lambda (x y) (* x y))) (div (lambda (x y) (/ x y)))) (lambda (name . args) ; dispatch function. note that args is a list (apply (case name ((add) add) ((sub) sub) ((mul) mul) ((div) div) (else (error 'object "invalid method"))) args)))) (object 'add 1 2) (object 'mul 2 2) (object 'mod 4 2)