At times, data mutability could be dangerous. So, i have tried to figure out “Why mutability is not required”
by performing operations on list in Python and Clojure.
In Python:
>>> lst = [12, 31, "foo"]
>>> lst.append(30) # append operation is destructive
>>> lst
>>> [12, 31, "foo", 30] # So, the actual list is modified
In Clojure:
user> (def lst '(12 31 "foo"))
#'user/lst
user> lst
(12 31 "foo")
user> (conj lst 10)
(10 12 31 "foo")
user> lst
(12 31 "foo") # the original list remains intact
Most objects in Clojure are immutable. When you really want mutable data, you must be explicit about it, by creating a mutable reference (ref) to an immutable object. You create a ref with
user> (def lst (ref ‘(12 31 “foo”)))
The ref wraps and protects access to its internal state. If you look at the ref itself, you will not see its contents:
user> lst
#<Ref@1b5a40a: (12 31 “foo”)>
To read the contents of the reference, you can call
user> (deref lst)
(12 31 “foo”)
You can use @ reader macro instead of deref function
user> @lst
(12 31 “foo”)
Now, you can modify the actual list like this
user> (dosync (alter lst conj 10))
(10 12 31 “foo”)
user> @lst
(10 12 31 “foo”) # Modified list
Conclusion: I am a python fan boy but clojure seems to be far better than python in terms of Data mutability.