Question

  1. (define self-add
    (let ((x 0))
      (lambda ()
        (set! x (+ x 1))
        x)))
    

(self-add) => 1

(self-add) => 2

(self-add) => 3

(self-add) => 4

    2.
 (define self-add1
    (lambda ()
      (let ((x 0))
        (set! x (+ x 1))
        x)))

(self-add1) => 1

(self-add1) => 1

(self-add1) => 1

Please tell me how to understand the difference between the above two functions? Thanks a lot in advance! Best regards.

Was it helpful?

Solution

The first function defines a local variable x with an initial value of 0 and afterwards binds a lambda special form to the name self-add - so x is "enclosed" by the lambda (that's why we say that the lambda from behaves as a closure) and will be the same for all invocations of self-add (you could say that x is "remembered" by self-add), and each time it gets called the value of x will be incremented by one.

The second function binds the lambda to the procedure and afterwards defines a local variable x inside the lambda - here x is redefined each time self-add1 gets called, and will be different for all invocations: so x is never "remembered" by self-add1 and is created anew every time the procedure gets called, initialized with 0 and then incremented, always returning the value 1.

OTHER TIPS

The first function is closure. You create x variable in the lexical scope of the function and the variable holds its value between calls.

Additional information:

First function is a closure, while second function simply returns the same function every time, which makes x = 0 and then adds one and returns the result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top