Atoms and swap! in Clojure
Tracks a visitor count and a front desk register in atoms, updating both through plain functions.
;; An atom holds one value that is allowed to change over time.
;; swap! applies a function to the current value and stores the
;; result, so the update stays a plain function call.
(def visitors (atom 0))
(swap! visitors inc)
(swap! visitors + 10)
(println (format "visitors %d" @visitors))
;; @ is deref: it reads the value in place without changing it.
(def register (atom {:desk "Ida" :guests []}))
(swap! register update :guests conj "Perez")
(swap! register update :guests conj "Okoye")
(println (format "%s logged %d" (:desk @register)
(count (:guests @register))))
;; reset! replaces the value outright instead of deriving a new one.
(reset! visitors 0)
(println (format "visitors %d" @visitors))
How it works
(swap! visitors inc)and(swap! visitors + 10)show thatswap!hands the current value to a function with any extra arguments after it.(swap! register update :guests conj "Perez")rebuilds a nested map, since the update function may return any value.@visitorsderefs the atom to read it, while(reset! visitors 0)replaces the value instead of deriving one.
Keywords and builtins used here
atomconjcountdefformatprintln
The run, in numbers
- Lines
- 19
- Characters to type
- 707
- Tokens
- 97
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 83 seconds.
Step 1 of 3 in State & records, step 22 of 27 in Language basics.