DEV Community

Cover image for Clojure 101 / atom
icncsx
icncsx

Posted on

2 2

Clojure 101 / atom

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}))
Enter fullscreen mode Exit fullscreen mode

Let's say we just got a mana boost.

(swap! player update :mana + 10)

(get @player :mana) ;; 60
Enter fullscreen mode Exit fullscreen mode

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay