开发者

Need help understanding bindings in Scheme code

For the code below, I am unable to comprehend how the bindings (x, y, z) occur. Please check out the code, I'll explain my problem in greater detail below:

(define (w x)
  (lambda (y z)
开发者_Python百科    (begin 
      (set! x (+ (* y x) z)) x)))
(define f1 (w 3))
(f1 4 2)
(f1 2 1)

The output is 14, 29. These are values for x.

This means initially, x=3, y=4, z=2. In the 2nd call, i.e. (f1 2 1), x=14, y=2,z=1.

My doubts:

How does the binding occur at first, why is x=3, y=4, and z=2? If it has got to do with lambda expression in the function, please elaborate on how it works..I have a feeling this is where my understanding breaks down..

Next, why is the initial answer of x=14 retained in the second call, i.e. (f1 2 1)?

Thank you for looking into this :)


When w is run, it creates a closure out of the inner lambda. Because x came from outside of that inner lambda, x is stored inside that closure (in this case, f1).

So, f1 has a variable inside that represents x, and it starts out as 3. When you run f1, it evaluates the math and then sets its own x to be 14.

The moral is, a lambda is more than just code; it's code combined with the variables it closes over, such as this x.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜