How to understand the parameter binding in macro definition in Lisp?
As shown in the below Lisp code,
(defvar a 1)
(defvar b 2)
(defmacro macro-add (c d)
`(开发者_运维技巧+ ,c ,d))
(macro-add a b)
The last line which calls the macro binds macro parameter c to passed in, does this mean c is bound to the symbol a or bound the the value which is bound to symbol a? More specifically, will c be evaluated to a or 1 in the macro context?
Macros are basically code transformers. They get code as input, destructured and bound to the macro parameters. They produce new code using arbitrary computation. For simple template-like code generation the backquote lists are popular.
Source code in Lisp is has two different appearances: the textual s-expressions and the interned so-called forms, which are already Lisp data. This transformation in done by the Lisp reader.
The macro transformation then is done on these Lisp forms. The result of this transformation is a new form. Eventually, after all macros are expanded, the resulting source code will then be evaluated. This picture is slightly wrong, but it helps to imagine that there are three independent phases: reading, macro expansion, execution.
In your case the source form is a list of three symbols: (macro-add a b)
. The first symbol names a macro, so the form will be macro expanded. The list is destructured: the first symbol is the macro name, the second symbol will be bound to C
and the third symbol will be bound to D
. With this arguments the macro now gets executed. As a result it produces a new form: a list of three items. The first item is the symbol +
, the second item is the value of C
, the symbol A
and the third item is the value of D
, the symbol B
. (+ A B)
is the result of the macro expansion.
The result of the macro expansion will now be macro expanded again, if necessary. Since +
in your code is not a macro, no macro expansion will be done. +
is a function. Now the ordinary evaluation takes place: compute the value of A
, compute the value of B
and then call +
with these two values to compute a new result value.
It's bound to the symbol 'a'. The parameters to a macro are basically not evaluated, in contrast to a function, where they are evaluated.
精彩评论