philipbohun.com

Glojure by Example: Atoms

Locals do not change. An atom is an identity that holds a value and can be swapped for a new one. @ reads the current value. swap! calls a function with that value and stores the result. reset! replaces the value outright.

(def total (atom 0))
(swap! total + 3)
(swap! total + 4)
(println @total)
(reset! total 0)
(println @total)

swap! on a map uses the same update functions as a plain map. A function can close over an atom and hand out the only way to change it.

(def person (atom {:name "Ada" :score 0}))
(swap! person update :score inc)
(println (:score @person))

(defn counter []
  (let [n (atom 0)]
    (fn [] (swap! n inc))))

(def next-id (counter))
(println (next-id))
(println (next-id))

swap! returns the new value, so the counter prints 1 and then 2.

$ glj atoms.glj
7
0
1
1
2

Next example: Exceptions.