Gabe Mc
Gabe Mc

Reputation: 473

How do you programatically create multiple compile-time defs in clojure?

I want to create multiple defs in a file at compile time without having to type everything out. I'd like to do something like:

(ns itervals)

(loop [i 0]
   (if (<= i 128)
       (do 
         (def (symbol (str "i" i)) i)
         (recur (+ i 1)))))

In that way, we define the variables i1,..., i128 in the current context. I can't figure out a way to do it at compile time without defining them all explicitly. I think macros might be the way to go, but I have no idea how.

Upvotes: 4

Views: 514

Answers (2)

John Lawrence Aspden
John Lawrence Aspden

Reputation: 17470

This feels more like compile time:

(defmacro multidef[n]   
    `(do ~@(for [i (range n)]
           `(def ~(symbol (str "i" i)) ~i))))

(multidef 128)

i0   ; 0 
i127 ; 127 
i128 ; unable to resolve

But I can't think of a test that will tell the difference, so maybe the distinction is false.

Upvotes: 7

Jeff the Bear
Jeff the Bear

Reputation: 5653

Try this:

(for [i (range 1 129)]
    (eval `(def ~(symbol (str "i" i)) ~i)))

Upvotes: 4

Related Questions