What About Global State?

Web Development with Clojure, Third Edition — by Dmitri Sotnikov, Scot Brown (79 / 107)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Polymorphism | TOC | Writing Code That Writes Cod e for You 👉

While predominantly immutable, Clojure provides support for shared mutable data, as well, via its STM library.[84] The STM ensures that all updates to mutable variables are done atomically. There are two major kinds of mutable types: the atom and the ref. The atom is used in cases where we need to do uncoordinated updates, and the ref is used when we might need to do multiple updates as a transaction.

Let’s look at an example of defining an atom and using it.

​ (​def​ global-val (​atom​ nil))

We’ve defined an atom called global-val, and its current value is nil. We can now read its value by using the deref function, which returns the current value.

​ (println (deref global-val))
​ =>nil

Since this is a common operation, there’s a shorthand for deref: the @ symbol. So writing (println @global-val) is equivalent to the preceding example.

Let’s look at two ways of setting a new value for our atom. We can either use reset! and pass in the new value, or we can use swap! and pass in a function that accepts the current value and updates it.

​ (​reset!​ global-val 10)
​ (println @global-val)
​ =>10
​ (​swap!​ global-val inc)
​ (println @global-val)
​ =>11

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.