Lucas Rudd
Lucas Rudd

Reputation: 415

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?

Upvotes: 9

Views: 2326

Answers (1)

Sam Estep
Sam Estep

Reputation: 13324

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])

Upvotes: 12

Related Questions