(def alice-height
(ref 3))
(def right-hand-bites
(ref 10))
(defn eat-from-right-hand []
(dosync
(when (pos? @right-hand-bites)
(alter right-hand-bites dec)
(alter alice-height #(+ % 24)))))
此代码来自 Living Clojure 一书。书中,作者还以为例进行了说明。更改 替换为 通勤 .我想知道
pos?
一开始的测试,真的可以做这个替换吗?
最佳答案
不,更换 alter
与 commute
递减时right-hand-bites
是不正确的。
有条件的意图显然是为了防止right-hand-bites
从变得消极。递减仅在 right-hand-bites
的假设下有效直到交易结束才会改变。同时,喜欢 alter
, commute
有自己的 ref 世界快照 View ,它将在提交时重新读取并重新应用通勤函数到 ref,这将是该程序中的一个错误。
所以,与 commute
可以将负值提交给 right-hand-bites
.
要么坚持 alter
,或使用 ensure
而不是 @
(尽管这使得整个通勤练习变得毫无意义)。
关于concurrency - 在下面的 Clojure 代码中,alter 可以替换为 Commute 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58955386/