-
(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.
The first function defines a local variable
xwith an initial value of0and afterwards binds a lambda special form to the nameself-add– soxis “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 ofself-add(you could say thatxis “remembered” byself-add), and each time it gets called the value ofxwill be incremented by one.The second function binds the lambda to the procedure and afterwards defines a local variable
xinside the lambda – herexis redefined each timeself-add1gets called, and will be different for all invocations: soxis never “remembered” byself-add1and is created anew every time the procedure gets called, initialized with0and then incremented, always returning the value1.