Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Can LISP macro be used to generate macro?

19 views
Skip to first unread message

KWS

unread,
Mar 22, 2011, 10:12:43 PM3/22/11
to
Hi,
I have a set of macro functions in the form of:
(defmacro foo-32 (x) `(the (signed-byte 32) ,x))
I would like to generate this set of functions (not only for 32)
inside a macro function.
My question: Is it possible?
If it is, Can anybody give some pointer?
Thanks
KWS

Joshua Taylor

unread,
Mar 22, 2011, 10:33:37 PM3/22/11
to

Sure... Macros can produce any kind of code you need, including code
that defines other macros. For instance, here's something along the
lines of what you showed:


(defmacro define-bytes (prefix sizes)
(let ((x (make-symbol "X")))
(flet ((make-name (suffix)
(intern (concatenate 'string
(string prefix) "-"
(write-to-string suffix)))))
`(progn
,@(mapcar #'(lambda (size &aux (name (make-name size)))
`(defmacro ,name (,x)
`(the (signed-byte ,,size) ,',x)))
sizes)))))

CL-USER > (pprint (macroexpand-1 '(define-bytes foo (8 16 32))))
(PROGN
(DEFMACRO FOO-8 (#:X) `(THE (SIGNED-BYTE 8) #:X))
(DEFMACRO FOO-16 (#:X) `(THE (SIGNED-BYTE 16) #:X))
(DEFMACRO FOO-32 (#:X) `(THE (SIGNED-BYTE 32) #:X)))


Those nested backquotes can be tricky, and you might find it easier to
work with the list structure directly rather than with the backquote
"templates":


(defmacro define-bytes (prefix sizes)
(let ((x (make-symbol "X")))
(labels ((make-name (suffix)
(intern (concatenate 'string
(string prefix) "-"
(write-to-string suffix)))))

`(progn
,@(mapcar #'(lambda (size)
(list 'defmacro (make-name size) (list x)
`(the (signed-byte ,size) ,x)))
sizes)))))


//JT

KWS

unread,
Mar 23, 2011, 2:15:48 AM3/23/11
to
Thanks Joshua.

0 new messages