I have just begun to learn about macros, and it would be really helpful if I could see what the expanded form of a specific macro looks like.
( using Lispworks)
is there a way to see the expanded form of a macro?
-
- Posts: 2
- Joined: Mon Aug 11, 2014 3:26 pm
-
- Posts: 61
- Joined: Mon Jul 07, 2008 8:06 pm
- Location: Toowoomba, Queensland, Australia
- Contact:
Re: is there a way to see the expanded form of a macro?
Sometimes your IDE will provide a context menu option if you right-click on an invocation of the macro. But the most common way is to use macroexpand or macroexpand-1 (see http://clhs.lisp.se/Body/f_mexp_.htm). The link has examples. I really recommend browsing the Common Lisp Hyperspec when you get spare moments, it has everything in standard Common Lisp in it.
-
- Posts: 61
- Joined: Mon Jul 07, 2008 8:06 pm
- Location: Toowoomba, Queensland, Australia
- Contact:
Re: is there a way to see the expanded form of a macro?
One other thing, I wrote this little helper macro to make expanding macros easy and readable:
The reason it's a macro is so that you don't have to quote the code you copy in (like you have to with macroexpand and macroexpand-1). Used like so:
which in Corman Lisp would output:
Code: Select all
(defmacro mac (form)
`(pprint (macroexpand-1 ',form)))
Code: Select all
(mac (setf (car hi) 5))
Code: Select all
(COMMON-LISP::%RPLACA HI 5)
-
- Posts: 2
- Joined: Mon Aug 11, 2014 3:26 pm
Re: is there a way to see the expanded form of a macro?
Thanks a lot. Very helpful, especially the "mac" macro.
( I had tried macroexpand myself, but obviously used it in a wrong way, like >>> (macroexpand-1 (form)) )
( I had tried macroexpand myself, but obviously used it in a wrong way, like >>> (macroexpand-1 (form)) )
-
- Posts: 61
- Joined: Mon Jul 07, 2008 8:06 pm
- Location: Toowoomba, Queensland, Australia
- Contact:
Re: is there a way to see the expanded form of a macro?
Cheers, glad I could help.
Many times it will be clearer when you know whether you're using a macro or a function (or a special form for that matter). Function calls all have standard evaluation rules, but macros can do what they want with evaluation (like not evaluate code in the case of mac, or evaluate things lots of times like loop). So when you know that macroexpand(-1) is a function, if you want to pass it code, you have to quote it.
