调整由 refs 列表组成的原子的值

adjusting the values of an atom which is made up of a list of refs

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

(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].

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

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

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