宏扩展:引用身体形式与否? [英] macro expansion: to quote the body forms or not?
问题描述
我很难确切了解宏扩展的工作原理。 elisp解释器处理这两个代码片段有什么区别?
I'm having a hard time understanding exactly how macro expansion works. What is the difference in how the elisp interpreter handles these two snippets of code?
(defmacro foo (arg)
(message "arg is: %s" arg))
(foo "bar")
和:
(defmacro foo (arg)
`(message "arg is: %s" ,arg))
(foo "bar")
推荐答案
您的示例可能会令人困惑,因为
You example may be confusing because
-
消息
都显示一条消息并返回。 - 字符串(如 bar)是自评估的。
message
both displays a message and returns it.- strings (like "bar") are self-evaluating.
教学示例
Instructive Example
(defconst zzz 123)
(defmacro zzz1 (arg)
`(insert (format "arg is: %s" ,arg)))
(defmacro zzz2 (arg)
(insert (format "arg is: %s" arg)))
在3种形式中的每一种之后使用 Cx Ce 评估以上代码。
Evaluate the code above using C-x C-e after each of the 3 forms.
现在评估以下内容:
解释器...
- 调用
zzz1
的宏函数 - 宏函数返回
(插入(格式为 arg is:%s zzz))
- 解释器评估该表单,并插入
arg是:123
进入当前缓冲区,并返回nil
(在底部的回显区域中看到)
- calls the macro function of
zzz1
- the macro function returns the form
(insert (format "arg is: %s" zzz))
- the interpreter evaluates the form, and inserts
"arg is: 123"
into the current buffer, and returnsnil
(seen in the echo area at the bottom)
第二版本:(zzz2 zzz)
解释器...
Second version: (zzz2 zzz)
The interpreter...
- 调用
zzz2
- 宏函数在当前缓冲区中插入
arg is:zzz
并返回nil
- 解释器将
nil
评估为nil
(在回显中看到
- calls the macro function of
zzz2
- the macro function inserts
"arg is: zzz"
in the current buffer and returnsnil
- the interpreter evaluates
nil
tonil
(seen in the echo are at the bottom)
最重要的
最重要的 -away是宏只是对代码进行操作的函数在编译器的解释器启动之前。
The bottom line
The most important "take-away" here is that macros are just functions which operate on code before the interpreter (of compiler) kicks in.
这些函数的参数未计算(即,在两个 zzz1
中)和 zzz2
, arg
是 zzz
,而不是 123
)。
These functions take their arguments unevaluated (i.e., in both zzz1
and zzz2
, arg
is zzz
, not 123
).
对它们的评估与其他任何lisp函数一样(例如,它们的主体中可以具有宏形式;主体被隐式 progn
;& c)。
They are evaluated like any other lisp function (e.g., they can have macro forms in their bodies; the body is wrapped in an implicit progn
; &c).
它们的返回值由解释器而不是原始格式评估。
Their return value is evaluated by the interpreter instead of the original form.
这篇关于宏扩展:引用身体形式与否?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!