Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 happens?

like image 957
salvador p Avatar asked Nov 21 '25 22:11

salvador p


1 Answers

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.

like image 98
dfan Avatar answered Nov 23 '25 13:11

dfan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!