Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating an atom with a single value

I have a number of atoms in my code where a common requirement is to update them to a new value, regardless of the current value.

I therefore find myself writing something like this:

(swap! atom-name (fn [_] (identity new-value)))

This works but seems pretty ugly and presumably incurs a performance penalty for constructing the anonymous closure.

Is there a better way?

like image 806
mikera Avatar asked Jun 17 '10 23:06

mikera


2 Answers

The reset! function should do this.

(reset! atom-name new-value)
like image 120
Pat Wallace Avatar answered Nov 01 '22 21:11

Pat Wallace


You can use (compare-and-set atom old-value new-value).

But I find it strange you need to change them so much to uncorrelated values. Can't you use bindings or similar things.

like image 22
Peter Tillemans Avatar answered Nov 01 '22 23:11

Peter Tillemans