Вопрос

I've been searching for a while and I can't find the proper question, so I will post it. I hope that is not posted already.

I understand what set! and let do, but I don't understand why set! can modifies a local variable of let and keep the value forever. For example:

(define count
  (let ((cont 0))
    (lambda ()
      (set! cont (+ cont 1))
      cont)))

If we evaluate (count) several times we see that the result is

> (count)
1
> (count)
2
> (count)
3
> 

... and so on. But, as far I understand, cont is a local variable, so why it keeps the value? Why it's not set to 0 every time the function is call?

Well, that is :) Thanks in advance!

PS: Excuse my English *o*

Это было полезно?

Решение

This happens because count is creating a closure that "stores" the value of cont, and it will remember its value even between procedure calls. Notice that the lambda is assigned to the count name after defining cont as a variable, and in doing so lambda closes over cont. It's no longer a local variable, its a variable that's defined outside the procedure and is being shared between all of its invocations, "remembering" the value it had in the last invocation.

For comparison, look how a procedure with truly local variables looks:

(define count
  (lambda ()
    (let ((cont 0))
      (set! cont (+ cont 1))
      cont)))

The above will always return 1, compare it with the procedure in the question.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top