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 t开发者_StackOverflow社区hem all explicitly. I think macros might be the way to go, but I have no idea how.
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.
Try this:
(for [i (range 1 129)]
(eval `(def ~(symbol (str "i" i)) ~i)))
精彩评论