3

I want to associate values of a map into an atom. I could do it like :

  (defonce config (atom {}))
  (swap! config assoc :a "Aaa")
  (swap! config assoc :b "Bbb")

But it is repetitive, and makes several calls to swap!. I would like to do something like that :

(swap! config assoc  {:a "Aaa"
                      :b "Bbb"})
;; this doesn't work :
;; Exception in thread "main" clojure.lang.ArityException: Wrong number of args (2) passed to: core$assoc

How do I do that ?

1 Answer 1

9

See the documentation for assoc:

=> (doc assoc)
-------------------------
clojure.core/assoc
([map key val] [map key val & kvs])
  assoc[iate]. When applied to a map, returns a new map of the
    same (hashed/sorted) type, that contains the mapping of key(s) to
    val(s). When applied to a vector, returns a new vector that
    contains val at index. Note - index must be <= (count vector).
nil

assoc doesn't take a map. It takes pairs of keys and vals:

user=> (assoc {} :a 1 :b 2)
{:a 1, :b 2}
user=> (let [x (atom {})]
                    #_=> (swap! x assoc :a 1 :b 2)
                    #_=> x)
#object[clojure.lang.Atom 0x227513c5 {:status :ready, :val {:a 1, :b 2}}]

By the way, you should always isolate your updates to an atom to a single swap!. By doing two swaps as above, you're allowing other threads to potentially clobber the referenced data. A single swap! keeps everything atomic.


N.B. merge behaves as you were imagining:

user=> (merge {} {:a 1 :b 1})
{:a 1, :b 1}
user=> (let [x (atom {})]
                    #_=> (swap! x merge {:a 1 :b 2})
                    #_=> x)
#object[clojure.lang.Atom 0x1be09e1b {:status :ready, :val {:a 1, :b 2}}]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.