计划中的关闭如何运作?
我在 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
>
函数调用内创建的每个 lambda 是否都会获取其作用域中每个变量的副本?它像某种隐式的 let 吗?我期望 lambda 具有某种指向它们创建范围的指针,使它们能够访问堆栈变量,但这告诉我事实并非如此,因为 f 和 f2 似乎有 x 的不同副本。到底发生了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您调用了
(makem)
两次,因此您使用x
的两个不同副本创建了两个不同的环境。如果您调用(makem)
一次,如下所示:那么
f
和f2
确实会共享相同的x
,m
中的那个。You called
(makem)
twice, so you created two different environments with two different copies ofx
. If you called(makem)
once, like so:then
f
andf2
would indeed share the samex
, the one inm
.