基本Lisp宏错误 [英] Basic Lisp Macro error
问题描述
请帮忙。我正在尝试创建此lisp宏,该宏将一个(数字)列表作为输入并返回这些数字的总和。代码
Little help here please . I am trying to create this lisp macro which takes a list (of numbers) as input and returns the sum of those numbers. The code
(setf g (list 1 2 3 4))
(defmacro add-test(var)
`(+ ,@var))
(添加测试g)
会出现此错误
The value G is not of type LIST.
[Condition of type TYPE-ERROR]
同时(add-test(1 2 3 4))
给出正确的结果为10。
At the same time (add-test (1 2 3 4))
gives the correct result which is 10.
请解释一下,为什么
其他详细信息-
Lispbox-SBCL
Lispbox - SBCL
Ubuntu Linux
Ubuntu Linux
预先感谢
推荐答案
这很简单,也是最常见的宏问题之一。
That's easy and one of the most common macro questions.
(add-test g)
现在进行宏扩展,宏 ADD-TEST
用参数 VAR
调用,得到值 G
,它是一个符号。
Now on macro expansion, the macro ADD-TEST
is called with the parameter VAR
getting the value G
, a symbol.
然后尝试进行列表操作。反引号表达式
Then you try a list operation. The backquote expression
`(+ ,@var)
VAR
的值是 G
,而您尝试将其拼接到列表(+ ...)
中。现在返回的表达式是(+。G)
。
The value of VAR
is G
, and you try to splice that into the list (+ ... )
. Now the returned expression is (+ . G)
.
CL-USER 12 > (macroexpand '(add-test g))
(+ . G)
T
(+。G)
不是有效的Lisp表单。
(+ . G)
is not a valid Lisp form. It's not valid source code.
记住,宏的参数是未经评估的源表达式。
Remember, the parameters to a Macro are the unevaluated source expressions.
比较
CL-USER 13 > (macroexpand '(add-test (1 2 3 4)))
(+ 1 2 3 4)
T
您说:'您能解释一下,当变量传入函数时为什么不起作用?'
You said: 'Can you please explain, why is it not working when variable is passed in to the function?'
记住, ADD-TEST
不是一个函数,它是一个宏。宏获取传递的源代码并返回一个新表单-然后对该表单进行评估。
Remember, ADD-TEST
is NOT a function, it is a macro. A macro gets the source code passed and returns a new form - that form is then later evaluated.
这篇关于基本Lisp宏错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!