Elisp中的高阶函数 [英] Higher-order functions in Elisp
问题描述
我创建了一个在Elisp中返回函数的函数:
I created a function that returns a function in Elisp:
(defun singleton-set (elem)
(defun f (n) (= n elem))
f)
我尝试运行这在IELM中,它失败:
I try to run this in IELM, and it fails:
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)
由于 Lisp-1和Lisp-2之间有什么区别?我改变了代码
(defun singleton-set (elem)
(defun f (n) (= n elem))
#'f)
并调用(funcall singleton-set 5)5)
,但现在的错误是
And invocation to (funcall (singleton-set 5) 5)
, but now the error is
***评估错误***符号值作为变量为void:elem
我从 elisp:从内部函数捕获变量这是由于Emacs Lisp的动态绑定。
I understand from elisp: capturing variable from inner function that this is due to dynamic binding of Emacs Lisp.
如何使Emacs Lisp中的函数返回函数?这种机制与其他语言(如Python,Scala或Clojure)不同的原因是什么?
How to make functions returning functions possible in Emacs Lisp? What is the reason this mechanism is different from other languages like Python, Scala or Clojure?
相关问题:
- elisp functions as parameters and as return value
- Elisp interactive function name
- How to Create a Temporary Function in Emacs Lisp
- In elisp, how do I put a function in a variable?
推荐答案
从Emacs 24的新闻
:
From the NEWS
for Emacs 24:
Emacs中的Lisp更改24.1
Lisp changes in Emacs 24.1
- 代码现在可以使用词法作用域,而不是动态范围。
lexical-binding
变量启用本地
变量的词法作用域。它通常通过文件的第一个
行中的文件局部变量进行设置,在这种情况下,它适用于该
文件中的所有代码。
- Code can now use lexical scoping by default instead of dynamic scoping.
The
lexical-binding
variable enables lexical scoping for local variables. It is typically set via a file-local variable in the first line of the file, in which case it applies to all the code in that file.
所以,在Emacs 24中:
So, in Emacs 24:
(setq lexical-binding t)
(defun singleton-set (elem) (lambda (n) (= n elem)))
(mapcar (singleton-set 1) '(0 1 2 3))
===> (nil t nil nil)
这篇关于Elisp中的高阶函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!