Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 282
Gabe Mc Avatar asked Dec 21 '22 19:12

Gabe Mc


2 Answers

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.

like image 85
John Lawrence Aspden Avatar answered May 19 '23 00:05

John Lawrence Aspden


Try this:

(for [i (range 1 129)]
    (eval `(def ~(symbol (str "i" i)) ~i)))
like image 24
Jeff the Bear Avatar answered May 18 '23 22:05

Jeff the Bear