Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining multiple constant variables in clojure

I'm trying to define several constant variables in clojure. Is there a way to define all of them in one def statement? Or must I define each one separately?

In any programming language (C++ Java) you may expect to be able to do the following

    const int x, y, z;
    x = y = z = 0;

However, in clojure I'm having trouble doing something similar with the def declaration. I've tried something based off of the 'let' syntax:

    (def ^:const [x 2 y 3 z 8])

and something like

    (def ^:const x 2 y 3 z 8)

but none of these work. Must I separately define each variable?

like image 381
Lucas Rudd Avatar asked May 19 '26 04:05

Lucas Rudd


1 Answers

If you want a separate Var for x, y, and z, you must define each one separately:

(def x 2)
(def y 3)
(def z 8)

You could easily write a macro to define multiple constants at once if this is too cumbersome:

(defmacro defs
  [& bindings]
  {:pre [(even? (count bindings))]}
  `(do
     ~@(for [[sym init] (partition 2 bindings)]
         `(def ~sym ~init))))

(defs x 2 y 3 z 8)

If these three constants are related, though, you could instead define a map with an entry for each number:

(def m {:x 2, :y 3, :z 8})

Depending on your use case, you may even find it valuable to define them as a vector instead:

(def v [2 3 8])
like image 190
Sam Estep Avatar answered May 21 '26 18:05

Sam Estep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!