tags:

views:

68

answers:

1
+3  A: 

That's easy and one of the most common macro questions.

(add-test 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) . 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) is not a valid Lisp form.

Remember, the parameters to a Macro are the unevaluated source expressions.

Compare that with the following:

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?'

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.

Rainer Joswig
Thanks Rainer for the detailed answer. That helped a lot.
bdev
Out of curiosity, let's say we take bdev's idea further. Suppose I have some sort of optimizable expression (a list of integers!), and I want to optimize the expression prior to "run-time". How would I do that? (although I suppose (eval G) might work...).
Paul Nathan
@Paul Nathan: you can EVAL it, COMPILE it, FUNCALL it, APPLY it - there are almost no limits. See also DEFINE-COMPILER-MACRO, which allows you to write optimizations.
Rainer Joswig
@Rainer - I finally found the solution for this -(defmacro add-test(x) `(+,@(evalx))) Thanks again for explaining this.
bdev
@Paul - Thanks for the 'eval' tip.
bdev
@bdev, eval also works only for some cases, btw. Can you imagine where EVAL does not help?
Rainer Joswig
@Rainer - I am not sure. But I think 'eval' can not be used inside an ordinary function as the function evaluates it's arguments automatically. Thanks.
bdev