Exercise 4.7. Let* is similar to let, except that the bindings of the let variables are performed sequentially from left to right, and each binding is made in an environment in which all of the preceding bindings are visible. For example
(let* ((x 3)
(y (+ x 2))
(z (+ x y 5)))
(* x z))
returns 39. Explain how a let* expression can be rewritten as a set of nested let expressions, and write a procedure let*->nested-lets that performs this transformation. If we have already implemented let (exercise 4.6) and we want to extend the evaluator to handle let*, is it sufficient to add a clause to eval whose action is
(eval (let*->nested-lets exp) env)
or must we explicitly expand let* in terms of non-derived expressions?
let* 表达式即 let 表达式的组合。
(let* ((x 3)
(y (+ x 2))
(z (+ x y 5)))
(* x z))
可以转化为
(let ((x 3))
(let ((y (+ x 2)))
(let ((z (+ x y 5)))
(* x z))))
我们的 let* 包如下:
(load "6-let.scm")
(define (install-eval-let*)
;;import let
(install-eval-let)
(define (make-let vars vals body)
((get 'constructor 'let) vars vals body))
(define (let*-body exp)
(cdr exp))
(define (let*-bindings exp)
(car exp))
(define (let*-vars bindings)
(map (lambda (x) (car x)) bindings))
(define (let*-vals bindings)
(map (lambda (x) (cadr x)) bindings))
(define (let*->nested-lets exp)
(define (combine bindings body)
(if (null? bindings)
body
(list ;; here we use list to construct let's body.
(make-let (let*-vars (list (car bindings)))
(let*-vals (list (car bindings)))
(combine (cdr bindings) body)))))
(car (combine (let*-bindings exp)
(let*-body exp))))
(define (eval-let* exp env)
(eval (let*->nested-lets exp) env))
(put 'eval 'let* eval-let*))
;;; tests begin
(let ((test-env (setup-environment)))
(install-eval-let)
(install-eval-let*)
(assert= (eval '(let* ((x 3)
(y (+ x 2))
(z (+ x y 5)))
(+ x z)) test-env)
16)
(eval '(define (f) (lambda (x) x)) test-env)
(assert= (eval '(let* ((x 3)
(y (+ x 3)))
((f) y) ;; this this a single statment!
)
test-env)
6)
(eval '(define (f2) (lambda () 3)) test-env)
(assert= (eval '(let* ((x 3)
(y (+ x 3)))
((f2)) ;; this this a single statment!
((f) y)
(+ ((f) y) ((f2)))
)
test-env)
9)
)