How To Construct a Map Conditionally in Clojure


I was wondering how to construct a multi-key map conditionally while I was coding in Clojure. Ideally, I would like to build it "in one pass" like {:bar 2 (when true :baz 3)}, but from what I had collected from Blue Sky, it seemed that's impossible, or it's just not an idiomatic way to program like that in Clojure. (Or, is this just a side effect of writing too much imperative code?)

Basically there are two ways, assoc / into / conj for collection manipulation, and cond-> (conditional thread-first) for general conditional operations.

;;; Using into
(into {:clojure 1} (when true {:elisp 2}))
;; => {:clojure 1, :elisp 2}

(into {:clojure 1} (when false {:elisp 2}))
;; => {:clojure 1}

;;; Using conj
(conj {:clojure 1} {:elisp 2} {:babashka 3})
;; => {:clojure 1, :elisp 2, :babashka 3}

(conj {:clojure 1} (when false {:elisp 2}))
;; => {:clojure 1}

;;; Using cond-> + assoc
(assoc {:clojure 1} :elisp 2 :babashka 3)
;; => {:clojure 1, :elisp 2, :babashka 3}

(cond->
    {:clojure 1}
  (= 1 1) (assoc :elisp 2)
  (= 2 1) (assoc :common-lisp 3))
;; => {:clojure 1, :elisp 2}

See also

comments powered by Disqus