SICP sicp 151: 4.7 exercises 1514.7 and
Exercise 4-7 original
Exercise 4.7. let * is similar to let, wait t that the bindings of the let variables are stored med 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?
Analysis
This question is very similar to the previous one. It is easy to grasp the key points in the question. That is to say, we can use list, car, And cdr to evaluate the value from left to right. The core idea is to use recursion to push forward to the right until exp is empty, return the body and end the construction. For tagged-list? These are the same as the previous questions.
Code
(define (let*? expr) (tagged-list? expr 'let*))(define (let*-body expr) (caddr expr))(define (let*-exp expr) (cadr expr))(define (let*->nested-lets expr) (let ((exp (let*-exp expr)) (body (let*-body expr))) (defien (make-lets exprs) (if (null? exprs) body (list 'let (list (car exprs)) (make-lets (cdr exprs))))) (make-lets exp)))