【发布时间】:2016-09-03 22:27:15
【问题描述】:
如果 eval 和 (interaction-environment) 应该可以访问在调用时的词法范围内定义的所有内容,那么为什么在尝试运行以下代码时会出现此错误?
Welcome to DrRacket, version 6.3 [3m].
Language: R5RS; memory limit: 128 MB.
why does this work? object_function: undefined;
cannot reference undefined identifier
代码:
(define (disp x)
(display x))
(eval '(disp "why does this work?") (interaction-environment))
;The below doesn't work
((lambda ()
(define (object_function x)
(display x))
(eval '(object_function "But not this?") (interaction-environment))))
(define (object)
(define (object_function x)
(display x))
(eval '(object_function "And not this?") (interaction-environment)))
(object)
如果我这样改变它:
;The below does work
(define (object_function x)
(display x))
((lambda ()
(eval '(object_function "Why does it work now?") (interaction-environment))))
(define (object)
(eval '(object_function "And now?") (interaction-environment)))
(object)
输出:
Welcome to DrRacket, version 6.3 [3m].
Language: R5RS; memory limit: 128 MB.
Why does it work now?And now?
单独使用 eval 可以正常工作,但是将其包装在定义的函数或 lambda 中,它无法找到与调用 eval 函数在同一范围内的本地定义的函数。
我可能会误解 eval 或 interaction-environment 如何处理词法范围,但如果有人能对此有所了解,那将会有所帮助。
【问题讨论】:
-
你的前提是错误的;
eval不应该访问它。interaction-environment是交互环境,而不是函数中的本地环境。
标签: scope scheme eval lexical-scope r5rs