Search code examples
lispcommon-lisp

Pop first element in a list using a macro


I have the following code

(defmacro popm(l)
`(prog1 (car ,l)
    (setf ,l (cdr ,l))))

which is supposed to pop the first element out of the list. However, I don't know how to call the macro. I tried using (popm (2 3 4)) but I get the error "EVAL: 2 is not a function name; try using a symbol instead". Can anyone point me in the right direction?


Solution

  • The correct way to debug macros is to use macroexpand-1:

    (macroexpand-1 '(popm (1 2 3)))
    (PROG1 (CAR (1 2 3)) (SETF (1 2 3) (CDR (1 2 3))))
    

    Now it should be clear why your macro does not work: it cannot be used with constant objects.

    It does work with variables though:

    (defparameter a '(1 2 3))
    (popm a)
    ==> 1
    a
    ==> (2 3)