Macro behavior issue in lisp

If in REPL I do this:

(dolist (x (1 2 3))
  (print x))

then I get an error, because in (1 2 3) the number 1 is not a symbol or lambda. If I do this:

(dolist (x (list 1 2 3))
      (print x))

then it works fine.

My question is this:

REPL> (defmacro test (lst)
           (dolist (x lst)
             (print x)))
=> TEST
REPL> (test (1 2 3))
1
2
3
=>NIL

Why does a dolist accept (1 2 3) when it is inside the macro definition, but not when directly in the repl? Assumption:

"Since TEST is a macro, it does not evaluate its arguments, therefore (1 2 3) is passed in the same way as for the Dolist macro. Therefore, the dolist should complain the same way as when it was passed (1 2 3) to REPL"

obviously wrong. But where?

UPDATE: although the answers help clarify some of the misunderstandings with macros, my question is still there and I will try to explain why:

, dolist ( 1, 2). , , , , , , ( 3). : . , , , , , . dolist ( backquotes def). (1 2 3) , , -. , , , (1 2 3) . , .

+3
5

. . dolist . , lst test:

(defmacro test (lst)
  (dolist (x lst)
    (print x)))

, dolist lst . , , (1 2 3).

+1

:

(defmacro test (lst)
  (dolist (x lst)
    (print x)))

, " ", . , , , :

(test (1 2 3))

:

(test (1 2 3))

, Lisp test , macro-extended, , (1 2 3), , . , :

(dolist (x '(1 2 3))
  (print x))

, . , , . Dolist nil , :

nil

nil nil, .

, . . " Lisp " " Lisp " .


: , , Lisp.

-, REPL : ( t e s t ( 1 2 3 ) ), : ( test ( 1 2 3 ) ).

: (test (1 2 3)). . , 'x (quote x).

, , (.. ). , (.. ), . , , , . test (1 2 3) , , ( , ) nil, ( ). macroexpansions.

, , , . nil ; nil.

, , .

+5

test . , . , :

( defmacro (lst)    `(dolist (x, lst)        ( x)))

+4

, , MACROEXPAND-1 - .

* (macroexpand-1 '(test (1 2 3)))

1 
2 
3 
NIL
T

IE, , - .

Nil - , DOLIST, .

+4

lst - , , eval dolist. - lst, lisp (1 2 3).

:

(test defmacro (a) (+ a 2))

(test 2) → 4; the middle function is call add, and the first variable is the binding of the value 2.

0
source

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


All Articles