Make vars constant for use in case statements in Clojure -
in clojure, there way make var constant such can used in case
statements?
e.g.
(def 1) (def b 2) (let [x 1] (case x :1 b :2 :none)) => :none
i understand can use cond
or condp
around this, nice if define not require further evaluation use case
.
as docstring tells you: no cannot this. can use chas emericks macro , however:
(defmacro case+ "same case, evaluates dispatch values, needed referring class , def'ed constants java.util.enum instances." [value & clauses] (let [clauses (partition 2 2 nil clauses) default (when (-> clauses last count (== 1)) (last clauses)) clauses (if default (drop-last clauses) clauses) eval-dispatch (fn [d] (if (list? d) (map eval d) (eval d)))] `(case ~value ~@(concat (->> clauses (map #(-> % first eval-dispatch (list (second %)))) (mapcat identity)) default))))
thus:
(def ^:const 1) (def ^:const b 2) (let [x 1] (case+ x :1 b :2 :none)) => :1
an alternative (which nice since it's more powerful) use core.match
's functionality. though can match against local bindings:
(let [x 2 a b b] (match x :1 b :2 :none)) => :2
Comments
Post a Comment