1

I am stuck trying to do something probably basic with clojure macro. I simplified my example to the minimal below. Let's say I have:

(def a {:i 0})

And I want to define b to something like:

(def b (my-func a a a a a a ... a a a a))

At compile time, I know how many a I want (for example 3). But to remove code redundancy, and for better code, I would like to parameterize the number of a. I would like something like:

(def b (my-func (some-magic-macro 3 a)))

that would expand to

(def b (my-func a a a))

Tried a bunch of things with macrodef, repeat, quoting etc... without much succes due to my limited understanding of clojure at this stage

Thank you people!

4
  • Why don't you just use repeat in the position of some-magic-macro? Perhaps you want this: (def b (apply my-func (repeat 3 a))). Commented Jun 29, 2015 at 6:42
  • ntalbs, what I need is to macro expand at compile time: I need to replace the following in my code: (def b (my-func a a a a a a ... a a a a)) by (def b (my-func (some-magic-macro 3 a))) that would expand (at compile time) to (def b (my-func a a a)) Commented Jun 29, 2015 at 6:57
  • @ntalbs Actually, this is very helpfull. Thanks! I am still very confused how and why, but that solve my problem :) Commented Jun 29, 2015 at 7:16
  • You can check apply function in the documentation. Study the difference that (+ 1 2 3 4 5) and (apply + [1 2 3 4 5]) will help you understand that. Commented Jun 29, 2015 at 9:36

1 Answer 1

4

As a macro returns a single form, you can't make my-magic-macro return a number of copies of the argument to be used by my-func. You can however include my-func as an argument to my-magic-macro, and have the complete call returned:

(defmacro my-magic-macro [func arg n] `(~func ~@(repeat n arg)))
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh I see. Indeed adding my-func as an argument makes it work. Thanks all for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.