Can someone help me understand how push can be implemented as a macro? The naive version below evaluates the place form twice, and does so before evaluating the element form:
(defmacro my-push (element place)
`(setf ,place (cons ,element ,place)))
But if I try to fix this as below then I’m setf-ing the wrong place:
(defmacro my-push (element place)
(let ((el-sym (gensym))
(place-sym (gensym)))
`(let ((,el-sym ,element)
(,place-sym ,place))
(setf ,place-sym (cons ,el-sym ,place-sym)))))
CL-USER> (defparameter *list* '(0 1 2 3))
*LIST*
CL-USER> (my-push 'hi *list*)
(HI 0 1 2 3)
CL-USER> *list*
(0 1 2 3)
How can I setf the correct place without evaluating twice?
Doing this right seems to be a little more complicated. For instance, the code for
pushin SBCL 1.0.58 is:So reading the documentation on get-setf-expansion seems to be useful.
For the record, the generated code looks quite nice:
Pushing into a symbol:
expands into
Pushing into a SETF-able function (assuming
symbolpoints to a list of lists):expands into
So unless you take some time to study
setf, setf expansions and company, this looks rather arcane (it may still look so even after studying them). The ‘Generalized Variables’ chapter in OnLisp may be useful too.Hint: if you compile your own SBCL (not that hard), pass the
--fancyargument tomake.sh. This way you’ll be able to quickly see the definitions of functions/macros inside SBCL (for instance, with M-. inside Emacs+SLIME). Obviously, don’t delete those sources (you can runclean.shafterinstall.sh, to save 90% of the space).