【发布时间】:2012-09-28 03:50:09
【问题描述】:
我在 Elisp 中创建了一个返回函数的函数:
(defun singleton-set (elem)
(defun f (n) (= n elem))
f)
我尝试在 IELM 中运行它,但它失败了:
ELISP> (singleton-set 5)
*** Eval error *** Symbol's value as variable is void: f
ELISP> ((singleton-set 5) 5)
*** Eval error *** Invalid function: (singleton-set 5)
由于What is the difference between Lisp-1 and Lisp-2?我把代码改成了
(defun singleton-set (elem)
(defun f (n) (= n elem))
#'f)
并调用(funcall (singleton-set 5) 5),但现在错误是
*** Eval error *** Symbol's value as variable is void: elem
我从elisp: capturing variable from inner function 了解到,这是由于 Emacs Lisp 的动态绑定造成的。
如何在 Emacs Lisp 中使函数返回函数成为可能?这种机制与 Python、Scala 或 Clojure 等其他语言不同的原因是什么?
相关问题:
【问题讨论】:
-
您不想在
singleton-set中使用defun。请改用(defun singleton-set (elem) #'(lambda ...))之类的东西,然后查看下面@geocar 的指针。
标签: emacs elisp higher-order-functions dynamic-binding