How do I add an element to an array-map in Clojure?

前端 未结 2 1486
野性不改
野性不改 2021-01-24 20:22

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

2条回答
  •  猫巷女王i
    2021-01-24 20:59

    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.

提交回复
热议问题