What about Global State?

While predominantly immutable, Clojure provides support for shared mutable data as well via its STM library.[79] 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, ...

Get Web Development with Clojure now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.