[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: defmacro with built-in gensym declaration and initialization

From: Robin Tarsiger
Subject: Re: defmacro with built-in gensym declaration and initialization
Date: Wed, 20 Jan 2021 10:47:01 -0600
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Thunderbird/78.6.0

Stefan Monnier wrote:
> Indeed, `macroexp-let2` was designed for similar situations.
> I'm not completely happy with it either, so if someone can design
> something better, that'd be welcome,

FWIW, I'm generally happy with the conveniences the Alexandria library
provides for in CL: 

once-only is similar to macroexp-let2* but cleaner and more convenient
(though it also acts like let rather than let*). Ad-hoc example:

  (defmacro strange-hypot (x y)
    (once-only (x y (z '(current-z-difference)))
      `(+ (* ,x ,x) (* ,y ,y) (* ,z ,z)))

  (macroexpand '(strange-hypot (+ x dx) 42))
  (LET ((#:X634 (+ X DX)) (#:Y635 42) (#:Z636 (CURRENT-Z-DIFFERENCE)))
    (+ (* #:X634 #:X634) (* #:Y635 #:Y635) (* #:Z636 #:Z636)))

Note that the "single evaluation as expanded of one macro argument"
case is very convenient, which is a big step up from Emacs's macroexp-

with-gensyms is closer to what akater was describing earlier, and is
a "lower-level" helper around let and gensym. Ad-hoc example:

  (defmacro vec3+nums-macro (v1 x2 y2 z2)
    (with-gensyms (v1-var x-var y-var z-var)
      `(let* ((,v1-var ,v1)
              (,x-var (+ ,x2 (elt ,v1-var 0)))
              (,y-var (+ ,y2 (elt ,v1-var 1)))
              (,z-var (+ ,z2 (elt ,v1-var 2))))
         (vec3 ,x-var ,y-var ,z-var))))

  (macroexpand '(vec3+nums-macro (acquire-vector (somehow))
                                 (+ previous-x dx) y -1.0))
         (#:X-VAR638 (+ (+ PREVIOUS-X DX) (ELT #:V1-VAR637 0)))
         (#:Y-VAR639 (+ Y (ELT #:V1-VAR637 1)))
         (#:Z-VAR640 (+ -1.0 (ELT #:V1-VAR637 2))))
    (VEC3 #:X-VAR638 #:Y-VAR639 #:Z-VAR640))

Note that the let* form is not convenient in once-only, and
the Alexandria helpers don't do any of the constant-related
optimization that Emacs's do AFAIK, but the possible slight
adjustments there are fairly obvious.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]