HomeMathEmailBlogGitHub

Atoms in Clojure

2023-05-11

Atoms in Clojure are a way to create mutable state within a program.

To declare an atom, use the atom function

(def my-atom (atom 0))

To get the value of an atom, use deref or @

(deref my-atom) ;=> 0
@my-atom ;=> 0

To modify the value stored in an atom, use swap!

swap!'s first parameter is the atom to be modified, followed by the function to modify it by and the parameters to that function.

(swap! my-atom inc)
@my-atom ;=> 1
(swap! my-atom #(+ %1 %2) 4)
@my-atom ;=> 5

It is also possible to conditionally modify atoms with compare-and-set!

Here, my-atom will only be changed if it is equal to the second parameter.

(compare-and-set! my-atom 6 100) ;=> false
@my-atom ;=> 5

(compare-and-set! my-atom 5 100) ;=> true
@my-atom ;=> 100