在clojure中定义多个常量变量

Luc*_*udd 3 variables const clojure

我试图在clojure中定义几个常量变量.有没有办法在一个def语句中定义所有这些?或者我必须单独定义每一个?

在任何编程语言(C++ Java)中,您可能希望能够执行以下操作

    const int x, y, z;
    x = y = z = 0;
Run Code Online (Sandbox Code Playgroud)

然而,在clojure中,我在使用def声明做类似的事情时遇到了麻烦.我尝试过基于'let'语法的东西:

    (def ^:const [x 2 y 3 z 8])
Run Code Online (Sandbox Code Playgroud)

和类似的东西

    (def ^:const x 2 y 3 z 8)
Run Code Online (Sandbox Code Playgroud)

但这些都不起作用.我必须单独定义每个变量吗?

Sam*_*tep 6

如果您想要单独的Var for x,yz,则必须单独定义每个:

(def x 2)
(def y 3)
(def z 8)
Run Code Online (Sandbox Code Playgroud)

如果这太麻烦,您可以轻松编写宏来一次定义多个常量:

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

(defs x 2 y 3 z 8)
Run Code Online (Sandbox Code Playgroud)

但是,如果这三个常量相关,则可以使用每个数字的条目定义一个映射:

(def m {:x 2, :y 3, :z 8})
Run Code Online (Sandbox Code Playgroud)

根据您的使用情况,您甚至可能会发现将它们定义为矢量很有价值:

(def v [2 3 8])
Run Code Online (Sandbox Code Playgroud)