Clojure 调整由引用列表组成的原子的值
我有一个原子,它包含一个引用列表。如何更新atom中的引用列表?我尝试了以下方法,但不起作用Clojure 调整由引用列表组成的原子的值,clojure,refs,Clojure,Refs,我有一个原子,它包含一个引用列表。如何更新atom中的引用列表?我尝试了以下方法,但不起作用 (def theatom (atom [])) (def mylist [1 2 3 4]) (reset! theatom (map ref mylist)) (swap! theatom (fn [anAtom] (map (fn [theRef] (dosync (alter theRef inc))) theatom) )) (println (map deref @thea
(def theatom (atom []))
(def mylist [1 2 3 4])
(reset! theatom (map ref mylist))
(swap! theatom (fn [anAtom]
(map (fn [theRef] (dosync (alter theRef inc))) theatom)
))
(println (map deref @theatom))
其想法是将每个ref值增加一个。
然后我应该打印[2 3 4 5]。你已经设置好了。我想你的意思是:
(swap! theatom (fn [refs]
(map (fn [theRef]
(dosync (alter theRef inc))
theRef) ; Returning the return of dosync "unwraps" the refs
refs)))
尽管可以使用doseq使其更整洁:
您试图映射原子而不是它所包含的列表。原子不可编辑,因此会引发错误。请从一开始就指出错误。我很确定我知道出了什么问题,所以我贴了一个答案。但是拥有所有的信息总是好的。这只是一个打字错误。将map fn[theRef]dosync alter theRef inc theatom更改为map fn[theRef]dosync alter theRef inc anAtom,然后将该参数更改为类似refs的值,因为它不是原子。另外,您确定这里需要引用吗?在您建议的更改之后,我得到错误:./clj tests.clj Exception(线程主java.lang.ClassCastException中的异常):java.lang.Long不能转换为java.util.concurrent.Future,我取消了删除我的答案。第二个错误是因为您调用map deref@theatom,因为您正在从dosync返回数字,dosync正在展开ref。不过,您确定此处需要ref吗?我需要使用refs,因为我需要对atom的内容进行事务处理。我正在处理一段更大的代码,但我似乎不知道如何调整原子内部的那些引用。
(swap! theatom (fn [refs]
(doseq [r refs]
(dosync (alter r inc)))
refs))