문제

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