Clojure交换原子与地图值

时间:2015-08-31 13:30:06

标签: clojure atomic

我希望assoc将地图的值添加到atom。 我可以这样做:

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

但这是重复的,并且多次调用swap!。 我想做那样的事情:

(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

我该怎么做?

1 个答案:

答案 0 :(得分:7)

请参阅{{else}}的文档:

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

顺便说一句,您应该始终将对原子的更新隔离为单个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}}] 。通过如上所述进行两次交换,您允许其他线程潜在地破坏引用的数据。单个swap!使一切都保持原子。

N.B。 swap!的行为与您想象的一样:

merge
相关问题