user236501
user236501

Reputation: 8648

Scheme Confusing of Let and Let*

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

With the code above, why is the answer 35, not 70? In the second let, x is 7 so z should be 7 + 3 = 10, and then the result should be 7 * 10 = 70. I know got another is let* I am very confusing between this 2. The sample is grabs from google. I already google but just can't get it.

Upvotes: 4

Views: 596

Answers (2)

user725091
user725091

Reputation:

To expand on Leppie's answer: if you had written

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

you would get the answer you expected. The internal let* is exactly equivalent to

(let ((x 7))
    (let ((z (+ x y)))
       (* z x)))

and in fact might be implemented that way in some Schemes.

In other words, in a let* form each successive binding after the first is in the scope of all the previously created bindings.

Upvotes: 5

leppie
leppie

Reputation: 117330

x is still bound to the outer let when calling (+ x y).

Upvotes: 2

Related Questions