Basic Lisp Macro Error

A little help here, please. I am trying to create this lisp macro that takes a list of (numbers) as input and returns the sum of these numbers. The code

(setf g (list 1 2 3 4))

(defmacro add-test(var)
    `(+ ,@var))

(add-test g) gives this error

The value G is not of type LIST.
[Condition of type TYPE-ERROR]

At the same time, (add-test (1 2 3 4))it gives the correct result, equal to 10.

Could you explain why it does not work when a variable is passed to a function?

Other information -

Lispbox - SBCL

Ubuntu linux

Thanks in advance

+3
source share
1 answer

This is a simple and one of the most common macro questions.

(add-test g)

Now, when expanding a macro, a macro ADD-TESTis called with a parameter VAR, receiving a value G, a character.

Then you try to perform a list operation. Backquote expression

`(+ ,@var)

VAR G, (+ ... ). (+ . G).

CL-USER 12 > (macroexpand '(add-test g))
(+ . G)
T

(+ . G) Lisp. .

, - .

:

CL-USER 13 > (macroexpand '(add-test (1 2 3 4)))
(+ 1 2 3 4)
T

: " , , ?"

, ADD-TEST , . - .

+9

Source: https://habr.com/ru/post/1765706/


All Articles