3

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)
    (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 :)

Roy
  • 763
  • 2
  • 8
  • 18

1 Answers1

4

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.

erjiang
  • 44,417
  • 10
  • 64
  • 100
  • well, the simple answer is that it's created by `lambda`. Once the `lambda` is run, the function is converted by Scheme into an internal closure (code + environment) that you probably can't see. – erjiang Dec 06 '10 at 19:21
  • this still puzzles me. How do you control how many variables are being created by your lambda expression that are internal? – Roy Dec 09 '10 at 07:22