Re: ONCE-ONLY



"Vladimir Zolotykh" <gsmith@xxxxxxxxxxxxx> writes:

> Hi,
>
> Let me ask you a question about ONCE-ONLY macro, which I've read in
> Practical Common Lisp by Peter Seibel, chapter 8. Macros: Defining
> Your Own. Do you think there is a way to explain how it works? The
> idea is understandable (I would appreciate if you corrected me): (1)
> macro can't be used standalone , only inside another macro,

Well, technically it *can* be used anywhere, but not necesarily to any
good effect. It's intended purpose is to be used within other macros.

> (2) its purpose is to evaluate each form passed as argument only
> once and in the proper order, (3) bind each result to the local
> variable and inside the BODY argument of this macro (4) use this
> variable instead the original macro parameter of the surrounding
> macro. Even my explanation is clumsy, not to mention my
> understanding of what's going on. However, the implemetation of the
> macro is (IMO) quite obscure.
>
> Here is the macro itself
>
> (defmacro once-only ((&rest names) &body body)
> (let ((gensyms (loop repeat (length names) collect (gensym))))
> `(let (,@(loop for g in gensyms collect `(,g (gensym))))
> `(let (,,@(loop for g in gensyms for n in names
> collect ``(,,g ,,n)))
> ,(let (,@(loop for n in names for g in gensyms
> collect `(,n ,g)))
> ,@body)))))
>
> and its simple usage
>
> (defmacro do-primes ((var start end) &body body)
> (once-only (start end)
> `(do ((,var (next-prime ,start)
> (next-prime (1+ ,var))))
> ((> ,var ,end))
> ,@body)))
>
> What I wanted to say in (4) is that: inside DO-PRIMES we have END as
> parameter, END as argument to ONCE-ONLY, and END inside the BODY
> argument to ONCE-ONLY. First two as far as I can judge is the same but
> the third is quite different, the last idea proved to be the most
> difficult to comprehend. Would you mind helpting me here?

Pascal gave a good walk-through of how this macro works. Let me just
say--mostly to folks who haven't looked at the book--that I presented
this macro in a sidebar more as a puzzle for the curious; I don't
really try to explain how it works and said so. Maybe someday--after I
finish building a Windows Lispbox--I'll write up something about how
it works and put it on the web.

-Peter

--
Peter Seibel peter@xxxxxxxxxxxxxxx

Lisp is the red pill. -- John Fraser, comp.lang.lisp
.



Relevant Pages