Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

immutability

Name: Anonymous 2011-12-29 20:17

Is there a benefit to immutable data structures like in Clojure and erlang? What does it do for you versus just not mutating mutable objects?

Name: Anonymous 2011-12-29 20:43

Sharing part of a data structure, thread safety, easier to reason about, easier to keep earlier versions of a data structure, unlocks the possibility of doing clever tricks behind the scenes.

Example of a ``clever trick'':
We have a list defined as a sequence of conses whose cdr is a cons or '(). The predicate list? has to cdr all the way up to the last element, and check whether it is null?. Since the list is immutable, when we cons something to '(), we know it will result in a list, and that cannot change, so (cons x y) can return a cons with some metadata saying it is a list whenever y is '(), or a list. The list? predicate is now O(1) instead of O(n).
The length of a list will also not change, we can make length O(1) instead of the usual O(n) in the same way: (length '()) is 0, (cons x '()) makes a list of length 1, (cons x y), where y is a list of length n, marks the returned cons to be a list of length n+1.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List