Assoc-if in Clojure

clojure

Is there an "assoc-if" function in the Clojure library? I.e if a value is truthy, update a map with a given key value. I've tried to find something to this effect, but came up lacking.

(defn assoc-if
  [m key value]
  (if value (assoc m key value) m))

Best Solution

If the goal is to avoid repeating m, you can use conj:

(conj m (when value [key value]))

...or Clojure 1.5's new threading macros:

(-> m
  (cond-> value (assoc key value)))

If it's actually important to avoid repeating both the m and value, you'll have to write your own or reach outside clojure.core

Related Question