(when (not= @a (swap! a transform)) (do-side-effect))
But it should be very clear to you that you need the semantics of concurrency. For example, another thread may change the atom between reading and replacing it:
- a = 1
- Topic 1 reads as 1
- Theme 2 changes to 2
- Topic 1 sweeps 2 to 2
- Thread 1 defines 1! = 2 and calls the do-side-effect
I donβt understand the question of whether this is desirable or undesirable. If you do not want this behavior, then the atom simply will not do the job unless you enter concurrency control with lock.
Seeing that you started with ref and asked about the atom, I think you probably already thought about concurrency. From your description, the ref approach seems to be better:
(when (dosync (not= @r (alter r transform)) (do-side-effect))
Is there a reason you don't like your decision?
If the answer is "because I don't have concurrency", then I would recommend that you use ref anyway. Actually there is no flaw, and this makes your semantics explicit. IMO programs tend to grow to the point where concurrency exists, and Clojure is really different about what should happen when it exists. (For example, oh, I'm just calculating things, oh, I'm just exposing this stuff as a web service now, oh, now I'm at the same time).
In any case, keep in mind that features like alter and swap! return a value, so you can use it for short expressions.
source share