Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Clojure使用映射值交换原子_Clojure_Atomic - Fatal编程技术网

Clojure使用映射值交换原子

Clojure使用映射值交换原子,clojure,atomic,Clojure,Atomic,我想将映射的值关联到原子中。 我可以这样做: (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 thr

我想将映射的值关联到原子中。 我可以这样做:

  (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

如何做到这一点?

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


N.B.
merge
的行为与您想象的一样:

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}}]
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}}]