gpt4 book ai didi

clojure - 比较和设置!无条件重置clojure 中的原子?

转载 作者:行者123 更新时间:2023-12-02 01:12:42 24 4
gpt4 key购买 nike

考虑 clojure repl 中的以下代码序列

(def elems (atom {}))
(swap! elems assoc 42 [:a 7])
elems

生成预期的 {42 [:a 7]}。现在试试

(compare-and-set! elems elems (atom {}))

产生 false,意味着 compare-and-set! 操作没有成功。我很惊讶,因为我希望 elems 测试与 compare-and-set! 操作中的 elems 相同。我知道我可以使用 reset! 来实现无条件重置原子的目标,但我想知道为什么 compare-and-set! 不完全正确一样吗?

最佳答案

compare-and-set! 作用于原子引用的值,而不是原子本身。

clojure.core/compare-and-set!
([atom oldval newval])
Atomically sets the value of atom to newval if and only if the
current value of the atom is identical to oldval. Returns true if
set happened, else false

你可能想要这个:

(compare-and-set! elems @elems {})

关于clojure - 比较和设置!无条件重置clojure 中的原子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15451721/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com