How do closures in Scheme work?
I tested the following code in Racket/DrScheme:
(define (makem)
(define x 34)
(list (lambda () (set! x (+ x 1)) x)
(lambda () (set! x (+ x 1)) x))
)
(define f (car (makem)))
(define f2 (car (cdr (makem))))
> (f)
35
> (f2)
35 ; I thought this would give me 36
> (f)
36
> (f)
37
>
Does every lambda created inside a function call get a copy of every variable in their scope? Is it like some sort of implicit let? I expected the lambdas to have some sort o pointer to the scope in which they were created, enabling them to access the stack variables, but this tells me otherwise, since f and f2 seem to have different copies of x. What exactly happ开发者_StackOverflow社区ens?
You called (makem)
twice, so you created two different environments with two different copies of x
. If you called (makem)
once, like so:
(define m (makem))
(define f (car m))
(define f2 (car (cdr m)))
then f
and f2
would indeed share the same x
, the one in m
.
精彩评论