提问人:Grim Oir-lee 提问时间:1/30/2021 最后编辑:dippasGrim Oir-lee 更新时间:1/31/2021 访问量:87
动态范围界定中的形式参数和自由变量
Formal parameters and free variables in dynamic scoping
问:
我对动态范围有些困惑,特别是当形式参数和自由变量共享名称时会发生什么。
例如
(define x 1)
(define f (lambda (x) x) )
(f 2)
如果使用动态范围编译和评估此代码,则输入将是什么?2 个还是 3 个?
虽然参数的赋值 (x = 2) 似乎是最“最新的”,所以它应该是“2”,但有些人告诉我答案是 1(其他人说是 2。每个人都很困惑)。
{我知道方案和大多数语言都使用词汇范围,但请告诉我的教授}
我将不胜感激我能得到的任何帮助。
答:
1赞
Will Ness
1/31/2021
#1
没有动态范围。它要么是“词法范围”,要么是“动态范围”。但是,撇开这一点不谈,它是 2:
(f 2)
=
( (lambda (x) x) 2 )
=
(begin (set! old-x x) ; save old value of formal param
(set! x 2) ; set param to argument's value
(set! return-value ; evaluate the body
x) ; and save the result
(set! x old-x) ; restore the param's old value
return-value ) ; return the result
转换必须始终使用临时变量的唯一名称,以防止任何混淆。这里是 和 但它可以是翻译后的程序代码中其他任何地方未使用的任何名称。old-x
return-value
评论