“如果"如何不评估其所有参数? [英] How does `if` not evaluate all its arguments?
问题描述
我正在尝试更深入地学习和理解Lisp编程语言.函数+
按照应用顺序评估其参数:
I'm trying to learn and understand the Lisp programming language to a deep level. The function +
evaluates its arguments in applicative order:
(+ 1 (+ 1 2))
先评估
(+ 1 2)
,然后评估(+ 1 3)
,但是if
函数的工作方式不同:
(+ 1 2)
will be evaluated and then (+ 1 3)
will be evaluated, but the if
function works differently:
(if (> 1 2) (not-defined 1 2) 1)
由于未评估(not-defined 1 2)
形式,因此程序不会中断.
As the form (not-defined 1 2)
isn't evaluated, the program doesn't break.
相同的语法如何导致不同的参数评估?如何定义if
函数,以便不评估其参数?
How can the same syntax lead to different argument evaluation? How is the if
function defined so that its arguments aren't evaluated?
推荐答案
if
is a special operator, not an ordinary function.
这表示复合形式中的rest
元素的正常规则在调用与first
元素关联的功能之前不适用(因为它类似于
This means that the normal rule that the rest
elements in the compound form are evaluated before the function associated with the first
element is invoked is not applicable (in that it is similar to macro forms).
The way this is implemented in a compiler and/or an interpreter is that one looks at the compound form and decides what to do with it based on its first
element:
- 如果它是一个特殊的运算符,它将执行其特殊的操作;
- 如果它是宏,则其宏功能会获得整体形式
- 否则,即使未定义函数,也将其视为函数.
- if it is a special operator, it does its special thing;
- if it is a macro, its macro-function gets the whole form;
- otherwise it is treated as a function - even if no function is defined.
请注意,可以将某些特殊形式定义为扩展为其他特殊形式的宏,但是实际上必须存在某些特殊形式.
Note that some special forms can be defined as macros expanding to other special forms, but some special forms must actually be present.
例如,可以根据 cond
来定义if
:
E.g., one can define if
in terms of cond
:
(defmacro my-if (condition yes no)
`(cond (,condition ,yes)
(t ,no)))
反之亦然(要复杂得多-实际上,cond
是一个宏,通常扩展为if
s的序列).
and vice versa (much more complicated - actually, cond
is a macro, usually expanding into a sequence of if
s).
PS.请注意,系统提供的宏和特殊运算符之间的区别,而技术上则清晰明了(请参阅 macro-function
),在思想上是因为这样
PS. Note that the distinction between system-supplied macros and special operators, while technically crisp and clear (see special-operator-p
and macro-function
), is ideologically blurred because
一个实现可以自由实现Common Lisp特殊运算符 作为宏.一个实现可以自由实现任何宏运算符 作为特殊运算符,但仅当 还提供了宏.
An implementation is free to implement a Common Lisp special operator as a macro. An implementation is free to implement any macro operator as a special operator, but only if an equivalent definition of the macro is also provided.
这篇关于“如果"如何不评估其所有参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!