0

我有一个包含参考列表的原子。我将如何更新原子内的参考列表?我尝试了以下但它不起作用。

(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))

这个想法是将每个参考值增加一。然后我应该打印 [2 3 4 5]。

4

1 回答 1

1

你把它设置得很奇怪。我想你的意思是:

(swap! theatom (fn [refs]
                 (map (fn [theRef]
                        (dosync (alter theRef inc))
                        theRef) ; Returning the return of dosync "unwraps" the refs
                      refs)))

尽管可以使用以下方法使其更整洁doseq

(swap! theatom (fn [refs]
                 (doseq [r refs]
                   (dosync (alter r inc)))
                 refs))

您试图映射原子而不是它所拥有的列表。原子不可迭代,因此会引发错误。

于 2018-05-09T21:17:39.303 回答