Eval and lexical variables

我的未来我决定 提交于 2019-12-06 08:18:18

First, though

(let ((x 1))
  (eval (1+ x)))

may look like it does work (it certainly does something), it is likely not doing, what you intend it to do. eval is a regular function, so it receives its arguments evaluated by the caller. Effectively, you are calling eval with an integer value of 2 -- which is then "evaluated" (since integers are self-quoting) to a result value of 2.

In

(defun foo (x form)
  (eval form))

it's easier to diagnose the failure. Run-time lexical bindings are not first-class objects, but something maintained by the interpreter/compiler behind the scenes. Regular functions (like eval) cannot access lexical variables defined at their call-sites.

One work-around would be to use special variables:

(defun foo (x form)
  (declare (special x))
  (eval form))

The declaration tells your lisp implementation, that x should be dynamically bound within its scope.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!