Lisp-在宏中使用`和`list` [英] Lisp- Usage of `'`and `list` in macros
问题描述
我正在尝试学习Elisp,因此我正在阅读Elisp的GNU手册.到目前为止,所有内容都很容易理解,但是当我阅读宏部分时,遇到了一些我很难理解的事情.我也真的找不到适当的解释:
I am trying to learn Elisp, so I am reading the GNU Manual for Elisp. Everything so far is easy to understand, however when I read to the section of macro I encountered something I have a hard time understanding. I couldn't really find an adequate explanation neither:
例如,一个简单的宏程序将变量加1:
For example, a simple macro program that increments the variable by 1:
(defmacro inc (var)
(list 'setq var (list '1+ var)))
我不确定为什么在 setq
和 1 +
前面有'
符号?这是否会使它们成为文字元素列表?(例如,包含三个元素的列表(setq var(1+ var))
I am not sure why there is '
symbol in front of setq
and 1+
? Won't this make them to a list of literal elements? (For example a list containing three elements (setq var (1+ var))
为什么我不能写:
; this seems more reasonable to me
(defmacro inc (var)
(setq var (1+ var))
我不太确定 list
在这里的工作方式,在这里使用 list
对我来说似乎很奇怪.有人可以向我解释吗?
I am not really sure how list
works here and it seems strange to me using list
here. Can someone explain to me?
推荐答案
这不会使它们成为文字元素列表吗?(例如,包含三个元素的列表
(setq var(1+ var))
确切地说是这样(如果我们将实际参数替换为 var
).
Precisely so (if we substitute the actual argument for var
).
宏会生成/返回 code .
这是扩展"宏的阶段,通常发生在elisp文件的字节编译期间.
This is the "expansion" phase of the macro, which typically takes place during byte-compilation of the elisp file.
就该字节编译的.elc文件的内容而言,在.el源文件中使用这两种方法之间没有什么区别:
So as far as the contents of that byte-compiled .elc file are concerned, there's no difference between you having used either of these things in your .el source file:
-
(inc foo)
-
(setq foo(1+ foo))
即在这两种情况下,要进行字节编译的代码都是(setq foo(1+ foo))
I.e. In both cases the code which gets byte-compiled is (setq foo (1+ foo))
在字节编译之外,当.el文件被 load
加载时,宏可能会被扩展;否则,在需要评估扩展的代码之前,应按需进行扩展(但是您应该始终假设扩展完全独立于后续评估而发生.
Outside of byte-compilation, a macro might be expanded when the .el file is load
ed or, failing that, on-demand right before the expanded code needs to be evaluated (but you should always assume the expansion happens completely independently of the subsequent evaluation).
这篇关于Lisp-在宏中使用`和`list`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!