각 클로저는 자기만의 저장 위치를 가질 수 있다.
같은 생성자가 만든 두 프로시저도 같은 코드를 실행하면서 서로 다른 바인딩을 기억할 수 있습니다.
같은 프로시저가 만든 두 카운터가 서로의 값을 덮어쓰지 않는 이유는 무엇일까요?
- Connect a closure to the environment where it was created
- Separate equal procedure code from distinct stored locations
- Predict observations from shared and private bindings
Each call to make-counter creates a new value binding and returns a procedure that keeps access to it. left and right share the lambda expression, but they do not share that binding.
The second example moves value outside both procedures. That single location is then shared, so an update through either procedure becomes the starting point for the other.
(begin
(define (make-counter start)
(let ((value start))
(lambda ()
(set! value (+ value 1))
value)))
(let ((left (make-counter 0))
(right (make-counter 10)))
(list (left) (left) (right) (left) (right))))- 출력
- —
- 값
- —
- 진단
- —
The first program returns (1 2 11 3 12).
Compare the two make-counter applications with the later calls to left and right. The repeated lambda body reaches the location captured by its own creation environment.
힌트를 보기 전에 프로그램을 바꿔 보세요.
Create a third counter starting at 100. Interleave all three counters and predict which calls can affect one another.
힌트 하나 보기
Count calls to make-counter. Each call creates one new private value binding.