加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Clojure交换原子与地图值

发布时间:2020-12-15 04:29:22 所属栏目:Java 来源:网络整理
导读:我想将地图的值与原子相关联. 我可以这样做: (defonce config (atom {})) (swap! config assoc :a "Aaa") (swap! config assoc :b "Bbb") 但它是重复的,并且几次调用交换! 我想做那样的事情: (swap! config assoc {:a "Aaa" :b "Bbb"});; this doesn't wo
我想将地图的值与原子相关联.
我可以这样做:

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

但它是重复的,并且几次调用交换!
我想做那样的事情:

(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没有拍摄地图.它需要成对的键和值:

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

顺便说一句,你应该总是将你对原子的更新隔离到一个交换!通过如上所述进行两次交换,您允许其他线程潜在地破坏引用的数据.单一交换!保持一切原子.

注:合并的行为与您想象的一样:

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,:b 2}}]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读