the little schemer - what is the difference between these two Scheme functions? -
(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 understand difference between above 2 functions? lot in advance! best regards.
the first function defines local variable x initial value of 0 , afterwards binds lambda special form name self-add - x "enclosed" lambda (that's why lambda behaves closure) , same invocations of self-add (you x "remembered" self-add), , each time gets called value of x incremented one.
the second function binds lambda procedure , afterwards defines local variable x inside lambda - here x redefined each time self-add1 gets called, , different invocations: x never "remembered" self-add1 , created anew every time procedure gets called, initialized 0 , incremented, returning value 1.
Comments
Post a Comment