关于 Common Lisp 中的 eval 函数
有人可以解释为什么函数 eval 的行为是这样的吗?
(eval (list 'cons t nil)) returns (T)
(eval (list 'cons 'a nil)) causes an error
(eval (list 'cons ''a nil)) returns (A)
多谢。
Can somebody explain why the function eval behaves like this?
(eval (list 'cons t nil)) returns (T)
(eval (list 'cons 'a nil)) causes an error
(eval (list 'cons ''a nil)) returns (A)
Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先:
T 是一个常量,求值时返回 T。 NIL 也是一个常量,计算结果为 NIL。 (CONS T NIL) 然后返回 (T . NIL),其缩写为 (T)。
第二:
A是一个变量。它可能是未定义的。当 A 未定义时,评估它会导致错误。
第三:
现在你应该考虑第三种形式......
First:
T is a constant and returns T when evaluated. NIL is also a constant and evaluates to NIL. (CONS T NIL) then returns (T . NIL), which is shorter written as (T).
Second:
A is a variable. It is possibly undefined. Evaluating it will lead to an error when A is undefined.
Third:
Now you should think about the third form...
您可能还需要注意的另一件事是,第三种形式是将符号 A 嵌入列表中。通常,这种形式主要在 Lisp 书籍中教授,用于通过 REPL 实验进行学习。然而,在实际的程序/函数中,您可能最初更多地使用在列表中放置由 A 表示的值或列表,而不是符号 A。
例如
(setf a 2)
(eval (list 'cons a nil)) => (2) [A 在列表评估之前评估; (eval '(cons 2 nil))]
(eval (list 'cons 'a nil)) => (2) [当 (eval '(cons a nil)) 被求值时,A 被求值]
(eval (list 'cons ''a nil)) => (A) [A 不会被评估,因为调用是 (eval '(cons 'a nil)); 'a 是符号 A]
如果您在开始时不执行 (setf a 2),第一种和第二种形式都会出错。这是因为当 a 被求值时,它是没有界限的(即粗略地说,它没有任何与之关联的值)
One more thing that you may want to note is that third form is embedding the symbol A in the list. Usually this is the form which is mostly taught in Lisp books for learning by experimenting on REPL. However in actual programs / functions, you may be using initially more of putting value or list represented by A in the list and not the symbol A.
e.g.
(setf a 2)
(eval (list 'cons a nil)) => (2) [A is evaluated before list is evaluated; (eval '(cons 2 nil))]
(eval (list 'cons 'a nil)) => (2) [A is evaluated when (eval '(cons a nil)) is evaluated]
(eval (list 'cons ''a nil)) => (A) [A does not get evaluated as call is (eval '(cons 'a nil)); 'a is symbol A]
If you don't do (setf a 2) in the beginning, 1st and 2nd both forms will give error. This is because when a is evaluated, it is not bounded (i.e. crudely, it does not have any value associated with it)