I read such a make-counter example from Section 2.9. Assignment of Scheme Programming
> (define make-counter
(lambda ()
(let ([next 0])
(lambda ()
(let ([v next])
(set! next (+ next 1))
v)))))
> (define count1 (make-counter))
> (count1)
0
> (count1)
1
I am very confused here, how is the state of 'next' maintained?
with my understanding,
(define count1 (make-counter)), return the value v,then the procedure of make-counter gone and destroyed,
When count1 was invoked again, a fresh make-counter called, so the expected results should be "0" constantly.
However, it magically print the following:
> (count1)
1
> (count1)
2
> (count1)
3
> (count1)
4
> (count1)
5
How the state of 'next' is kept?
No,
make-counteris not called again. It is the innermost lambda that is called again, because(make-counter)returned the innermost lambda.To see this more clearly, rewrite
make-counterlike this:To see it even more clearly, get rid of
make-counter:Every time you execute
(count1), you are executing the body of the lambda.Even if you call
(count1)over and over again,nextwill not become0, because(count1)will only execute the body of the lambda.nextwas only set to0whencount1was initially defined.