Refs and Software Transactional Memory
Most objects in Clojure are immutable. When you really want mutable data, you must be explicit about it, such as by creating a mutable reference (ref) to an immutable object. You create a ref with this:
(ref initial-state) |
For example, you could create a reference to the current song in your music playlist:
(def current-track (ref "Mars, the Bringer of War")) | |
-> #'user/current-track |
The ref wraps and protects access to its internal state. To read the contents of the reference, you can call deref:
(deref reference) |
The deref function can be shortened to the @ reader macro. Try using both deref and @ to dereference current-track:
(deref current-track) | |
-> "Mars, the Bringer of War" |
Get Programming Clojure, 2nd Edition 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.