简体   繁体   中英

Why macroexpansion doesn't expand nested forms in 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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM