SICP Exercise 4.7 let*

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?

SOLUTION

E X P L A N A T I O N

(let* ((x 3) (y (+ x 2)) (z (+ x y 5)))
    (* x z)
)

can be written as:

(let ((x 3))
    (let ((y (+ x 2)))
        (let ((z (+ x y 5)))
            (* x z)
        )
    )
)

As can be seen below in the "let*" section, it is sufficient to add a clause to EVAL whose action is:

(eval (let*->nested-lets exp) env)

There is no need to explicitly expand let* in terms of non-derived expressions.

The code and tests are here.

Comments

Popular posts from this blog

SICP Exercise 2.56 differentiation rule

SICP Exercise 1.28 (Miller-Rabin Test)

SICP Exercise 4.18 a alternative strategy for interpreting internal definitions