How can I add an element to an array-map in Clojure? I tried using assoc but it doesn\'t get added? I essentially want to set a default value of 0 for any missing items in the e
To supplement Carcigenicate's answer, another suggestion:
I'd use merge
or assoc
on a map of defaults:
(merge {:default-1 123 :default-2 234} {:default-1 "foo"})
=> {:default-1 "foo", :default-2 234}
Note that the order of arguments to merge
matters i.e. right-most maps take precedence over left-most maps. Your default map values will only "survive" if they're not overridden by additional map(s).
(def defaults {"foo" 0, "bar" 0})
(defn create-entry [doc]
(assoc defaults "id" (str (java.util.UUID/randomUUID))))
(defn create-entry [doc]
(merge defaults {"id" (str (java.util.UUID/randomUUID))}))
Using assoc
in this example has the same effect, and I'd prefer that version.