Most of the data structures you encounter in Clojure are immutable. When you conj
to a list, or when you assoc
to a map, you end up with a brand list and map respectively. Sometimes, though, you will have to mutate data. This is where an atom comes in.
Suppose you are keeping track of a player's state - namely mana and health, and because we have many "components" that subscribe to the player's state, we need to mutate the state instead of simply returning one like we're used to.
To update the value of an atom, we can use the swap!
function.
(def player (atom {:health 100
:mana 50}))
Let's say we just got a mana boost.
(swap! player update :mana + 10)
(get @player :mana) ;; 60
You might be wondering: what's with the @?
Think of an atom as a reference type. To get the value of an atom, you must deference it with @.
If you know C++, it can help to think of atoms as like pointers in C++. To get the value pointed at by a pointer variable, we use *ptr
in C++. In Clojure, we use @atom
.
I hope you got the point. I'm out.
Warmly,
DH
Top comments (0)