3 ms·
with macros in Lisp tend to be sanely designed: they explicitly list the symbols that are to be introduced into the scope. I don't think I've never seen a "brin
by kazinator 6y ago
with macros in Lisp tend to be sanely designed: they explicitly list the symbols that are to be introduced into the scope. I don't think I've never seen a "bring the whole set of the currently defined slots of this class/struct into this scope as locals".
Oh, you can do it.
his is the TXR Lisp interactive listener of TXR 249.
Quit with :quit or Ctrl-D on an empty line. Ctrl-X ? for cheatsheet.
Use full-strength TXR for tough tasks, or dilute with shell scripts.
1> (defmacro with (struct obj . body)
(with-gensyms (obj-sym)
^(let ((,obj-sym ,obj))
(symacrolet ,(mapcar (op list @1 ^(qref ,obj-sym ,@1)) (slots struct))
,*body))))
with
2> (with time (time-struct-utc (time))
(list year month day))
(2021 1 30)
Expansion:
3> (macroexpand '(with time (time-struct-utc (time))
(list year month day)))
(let ((#:g0016 (time-struct-utc (time))))
(symacrolet ((time-local
#:g0016.time-local)
(time-utc #:g0016.time-utc)
(time-string
#:g0016.time-string)
(time-parse #:g0016.time-parse)
(year #:g0016.year)
(month #:g0016.month)
(day #:g0016.day)
(hour #:g0016.hour)
(min #:g0016.min)
(sec #:g0016.sec)
(dst #:g0016.dst)
(gmtoff #:g0016.gmtoff)
(zone #:g0016.zone))
(list year month
day)))
Total expansion; symacrolet gone, a.b desugared into (slot a 'b):
4> (expand '(with time (time-struct-utc (time))
(list year month day)))
(let ((#:g0017 (time-struct-utc (time))))
(list (slot #:g0017 'year)
(slot #:g0017 'month)
(slot #:g0017 'day)))