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
push
in 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
symbol
points 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
--fancy
argument 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.sh
afterinstall.sh
, to save 90% of the space).Taking a look at how the existing one (in SBCL, at least) does things, I see:
So, I imagine, mixing in a combination of your version and what this generates, one might do:
A few observations:
This seems to work with either
setq
orsetf
. Depending on what problem you're actually trying to solve (I presume re-writingpush
isn't the actual end goal), you may favor one or the other.Note that
place
does still get evaluated twice... though it does at least do so only after evaluatingelement
. Is the double evaluation something you actually need to avoid? (Given that the built-inpush
doesn't, I'm left wondering if/how you'd be able to... though I'm writing this up before spending terribly much time thinking about it.) Given that it's something that needs to evaluate as a "place", perhaps this is normal?Using
let*
instead oflet
allows us to use,el-sym
in the setting of,new-sym
. This moves where thecons
happens, such that it's evaluated in the first evaluation of,place
, and after the evaluation of,element
. Perhaps this gets you what you need, with respect to evaluation ordering?I think the biggest problem with your second version is that your
setf
really does need to operate on the symbol passed in, not on agensym
symbol.Hopefully this helps... (I'm still somewhat new to all this myself, so I'm making some guesses here.)