ghivert
ghivert

Reputation: 548

Expanding macros in macros

I have the following macro :

(defmacro add-children [this children]
  (map (fn [child] (list '.addChild this child)) children))

and I would like to create the following macro :

(defmacro defgom [name & body]
 (let [sym (gensym)]
  `(let [~sym (Model.)]
     (add-children sym body)))))

Considering that Model is a Java class with an addChild function. I would like to expand defgom to

(let [*gensym* (Model.)]
  (.addChild *gensym* (first body))
  (.addChild *gensym* (second body))
  ...
  (.addChild *gensym* (last body)))

When evaluated, the add-children macro gives the correct result (the list of .addChild). But I can't evaluate it in the defgom macro. I get a "Don't know how to create ISeq from: clojure.lang.Symbol". I tried with ~ or ~@ (given that add-children returns a list), but none worked.

How to properly expand the macro inside the macro?

PS: I know I can do it with a function rather than the add-children macro, but I want to know if it's possible to do it with a macro.

Upvotes: 0

Views: 82

Answers (1)

amalloy
amalloy

Reputation: 92117

Just change the last line to:

(add-children ~sym ~@body)

Upvotes: 2

Related Questions