【问题标题】:Scheme - How can eval recognize a variable?方案 - eval 如何识别变量?
【发布时间】:2015-10-11 07:12:35
【问题描述】:

例如,如果我定义一个函数:

(define (^ x y) (expt x y))

然后 eval 可以识别 (^ 3 3) 并对其进行评估,但我需要它来评估从输入中读取的变量(不是恒定的,这意味着如果读取了相同的变量,则可以稍后更改它们具有不同的值)。

有没有办法 eval 可以识别变量?

【问题讨论】:

  • 我觉得这是XY problem。在 R5RS 中,eval 有第二个参数。一个可选过程是interaction-environment,它返回当前环境,但对于拥有它的实现,它会做你想做的事。不过,您仍然不会得到词法变量。在R6RS 中这是不可行的,因为您只能从库中导入。

标签: variables scheme eval


【解决方案1】:

如何使用 eval 的确切约定因实现而异 - 因此最好的建议是在您的 Scheme 实现的文档中查找 eval

也就是说,R5RS 中eval 的官方文档说:

procedure:  (eval expression environment-specifier) 

Evaluates expression in the specified environment and returns its value. 
Expression must be a valid Scheme expression represented as data, 
and environment-specifier must be a value returned by one of the three
procedures described below. Implementations may extend eval to allow non-
expression programs (definitions) as the first argument and to allow other
values as environments, with the restriction that eval is not allowed to 
create new bindings in the environments associated with null-environment or 
scheme-report-environment.


(eval '(* 7 3) (scheme-report-environment 5))
                                                           ===>  21

(let ((f (eval '(lambda (f x) (f x x))
               (null-environment 5))))
  (f + 10))
                                                           ===>  20

【讨论】:

    猜你喜欢
    • 2019-07-03
    • 1970-01-01
    • 2018-08-19
    • 2016-08-25
    • 1970-01-01
    • 2018-06-03
    • 2019-04-24
    • 2017-04-18
    • 1970-01-01
    相关资源
    最近更新 更多