gpt4 book ai didi

Clojure 交换原子与映射值

转载 作者:行者123 更新时间:2023-12-01 09:21:29 24 4
gpt4 key购买 nike

我想将 map 的值关联转换为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

我该怎么做?

最佳答案

查看 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 不带 map 。它需要成对的键和值:

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!。通过如上所述进行两次交换,您允许其他线程潜在地破坏引用的数据。单个 swap! 保持一切原子性。


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

关于Clojure 交换原子与映射值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32312478/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com