为什么我们需要在Lisp中进行funcall? [英] Why do we need funcall in Lisp?
问题描述
为什么我们必须使用funcall
来调用Common Lisp中的高阶函数?例如,为什么我们必须使用:
Why do we have to use funcall
to call higher order functions in Common Lisp? For example, why do we have to use:
(defun foo (test-func args)
(funcall test-func args))
而不是简单的:
(defun bar (test-func args)
(test-func args))
来自程序背景,我对此感到有些惊讶,因为我比较习惯的语言(例如Python,C#)不需要区别.特别是,至少在源代码级别,C#编译器将其转换为类似func.invoke()
的内容.
Coming from a procedural background, I'm a bit surprised by that since the languages I'm more used to (e.g. Python, C#) don't need the distinction. In particular, on the source level at least, the C# compiler transforms it to something like func.invoke()
.
我看到的唯一问题是,这将意味着我们无法再调用全局函数test-func
,因为它会被遮蔽,但这并不是问题.
The only problem I see is that this would mean we couldn't call a global function test-func
anymore because it'd be shadowed, but that's hardly a problem.
推荐答案
严格来说,不需要funcall
,但是有一些lisps(列表2的实现,例如Common Lisp)将分开. 函数名称空间的变量名称空间. List-1实现(例如Scheme)没有区别.
Strictly speaking, funcall
would not be needed, but there are some lisps (list-2 implementations, such as Common Lisp) that separate the variable name space of the function name space. List-1 implementations (e.g. Scheme) do not make this distinction.
更具体地说,在您的情况下,test-func
在变量名称空间中.
More specifically, in your case, test-func
is in the variable name space.
(defun foo (test-func args)
(funcall test-func args))
因此,您需要一个在变量名称空间中实际搜索与此变量关联的功能对象的构造.在Common Lisp中,此构造为funcall
.
Therefore you need a construct that actually searches the function object associated with this variable in the variable name space. In Common Lisp this construct is funcall
.
另请参见此答案.
这篇关于为什么我们需要在Lisp中进行funcall?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!