Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: immutability and persistence

Every textbook says that Clojure data structures are 'immutable and persistent'. They go different lengths explaining the concept, but so far I failed to figure out what is the difference between immutability and persistence. Is there an entity persistent but mutable? or immutable but not persistent?

like image 699
Alexey Orlov Avatar asked Nov 26 '14 15:11

Alexey Orlov


2 Answers

Immutable means that the value can't be changed and persistence means that the path to the value is copied if the value already exists within the program. Clojure uses this as a part of it's structural sharing implementation. If the data doesn't exist, it's created. If the data exists, the new data builds on the old version of the data without altering or removing it.

Atoms are persistent but safely mutable.

user> (def +a+ (atom 0))
#'user/+a+
user> @+a+
0
user> (swap! +a+ inc)
1
user> @+a+
1

Transients are mutable but should be made persistent after mutation

user> (def t (transient []))
#'user/t
user> (conj! t 1)
#<TransientVector clojure.lang.PersistentVector$TransientVector@658ee462>
user> (persistent! t)
[1]

Understanding Clojure's Persistent Vectors, pt. 1 => http://hypirion.com/musings/understanding-persistent-vector-pt-1

Persistent data structure => https://en.wikipedia.org/wiki/Persistent_data_structure

Persistent Data Structures and Managed References => http://www.infoq.com/presentations/Value-Identity-State-Rich-Hickey

like image 173
runexec Avatar answered Sep 24 '22 17:09

runexec


Purely Functional Data Structures by Chris Okasaki refers to an article [1] which appears to contain the original definition of the term persistent:

Ordinary data structures are ephemeral in the sense that making a change to the structure destroys the old version, leaving only the new one. … We call a data structure persistent if it supports access to multiple versions. The structure is partially persistent if all versions can be accessed but only the newest version can be modified, and fully persistent if every version can be both accessed and modified.

[1] James R. Driscoll, Neil Sarnak, Daniel D. Sleator, and Robert E. Tarjan. Making data structures persistent. Journal of Computer and System Sciences, 38(1):86–124, February 1989.

like image 45
Mike Fikes Avatar answered Sep 21 '22 17:09

Mike Fikes