Reb.Cabin
Reb.Cabin

Reputation: 5567

compare-and-set! to unconditionally reset an atom in clojure?

Consider the following sequence of code in the clojure repl

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

producing the expected {42 [:a 7]}. Now try

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

producing false, meaning the compare-and-set! operation did not succeed. I am surprised, because I expected elems to test identical to elems inside the compare-and-set! operations. I am aware that I can use reset! to accomplish the goal of unconditionally reset the atom, but I want to know why compare-and-set! doesn't do exactly the same?

Upvotes: 2

Views: 506

Answers (1)

mtyaka
mtyaka

Reputation: 8848

compare-and-set! works on values referenced by atoms, not on atoms themselves.

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

You probably want this:

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

Upvotes: 6

Related Questions