Skip to Main Content
Programming Clojure, 3rd Edition
book

Programming Clojure, 3rd Edition

by Alex Miller, Stuart Halloway, Aaron Bedra
February 2018
Intermediate to advanced content levelIntermediate to advanced
304 pages
7h 11m
English
Pragmatic Bookshelf
Content preview from Programming Clojure, 3rd Edition

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"
 
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Kotlin

Programming Kotlin

Venkat Subramaniam
Getting Clojure

Getting Clojure

Russ Olsen

Publisher Resources

ISBN: 9781680505719Errata Page