Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why macroexpansion doesn't expand nested forms in Clojure?

Tags:

macros

clojure

I don't understand how to get the full macro expansion.

With this code

(when true (when true true))

I would like to get the full macro expansion

(if true (do (if true (do true)))

But I can't

I understand macroexpansion-1 will resolve the first level of expansion :

(macroexpand-1 '(when true (when true true)))

(if true (do (when true true)))

But why when I call again macroexpand-1 (that's what should do macroexpand) :

(macroexpand-1 '(if true (do (when true true))))

I got the exact same result ?

(if true (do (when true true)))

I was expecting a full macro expansion.

Does macro expansion only works with top level forms ?

I'm aware of an expand-all function in the clojure.walk namespace, so I suppose macroexpand doesn't work on nested structures. Am I right ?

like image 873
Demeter Purjon Avatar asked Dec 07 '25 08:12

Demeter Purjon


1 Answers

You are right.

See also https://clojuredocs.org/clojure.core/macroexpand

Where it states :

Note neither macroexpand-1 nor macroexpand expand macros in subforms.

And indeed macroexpand-all does the recursive expansion :

> (clojure.walk/macroexpand-all '(when true (when true true))) 
(if true (do (if true (do true))))

See also https://clojuredocs.org/clojure.walk/macroexpand-all

where it states :

Recursively performs all possible macroexpansions in form.

Your example

(macroexpand-1 '(if true (do (when true true))))

might confuse you, but it does as the docs tell :

(macroexpand-1 form) If form represents a macro form, returns its expansion, else returns form.

So since 'if' is not a macro, it just returns if, without going into subforms...

like image 114
Peter Avatar answered Dec 10 '25 04:12

Peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!