is there a way to see the expanded form of a macro?

Discussion of Common Lisp
Post Reply
gmannerheim
Posts: 2
Joined: Mon Aug 11, 2014 3:26 pm

is there a way to see the expanded form of a macro?

Post by gmannerheim » Sun Aug 17, 2014 12:01 pm

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)

Kohath
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?

Post by Kohath » Mon Aug 18, 2014 10:46 pm

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.

Kohath
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?

Post by Kohath » Mon Aug 18, 2014 10:54 pm

One other thing, I wrote this little helper macro to make expanding macros easy and readable:

Code: Select all

(defmacro mac (form)
  `(pprint (macroexpand-1 ',form)))
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:

Code: Select all

(mac (setf (car hi) 5))
which in Corman Lisp would output:

Code: Select all

(COMMON-LISP::%RPLACA HI 5)

gmannerheim
Posts: 2
Joined: Mon Aug 11, 2014 3:26 pm

Re: is there a way to see the expanded form of a macro?

Post by gmannerheim » Tue Aug 19, 2014 7:29 pm

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)) )

Kohath
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?

Post by Kohath » Tue Aug 19, 2014 9:37 pm

Cheers, glad I could help. :idea: 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.

Post Reply