Saturday, January 12, 2013

On Immutablity

"And yet in our world everybody thinks of changing humanity, but nobody thinks of changing himself."
Three Methods of Reform by Leo Tolstoy

"When Moses was alive, these pyramids were a thousand years old. Here began the history of architecture. Here people learned to measure time by a calendar, to plot the stars by astronomy and chart the earth by geometry. And here they developed that most awesome of all ideas - the idea of eternity."
Walter Cronkite

In my best Yogi Berra, eternity is a rather long time, even longer than now.  One finds very quickly when learning about functional programming the idea of immutability.  In functional programming one does not find variables in the true since of the word, instead one hears of binding to a value or value functions.  Why is this?  What does this have to do with immutability?

Much like how Immanuel Kant's categorical imperative forbids lying, functional programming forbids mutating values.  This means you cannot say that foo is equal to 5 at one point in time and later on say that now foo is equal to 6.  You have just lied, which one is it, 5 or 6?  Even worst is it now 7?  Immutability solves this be not allowing you to change the value of foo once you say that foo is equal to 5.

One may at this time being saying, "How is immutability useful?  I have been programming for X number of years and that whole time I have been using variables and nothing bad as been happen!"  If we travel back in time a few decades, we can hear a similar argument about GOTO statements.

Why immutability now?  Well, as Uncle Bob points out in his first post about functional programming there is a tide wave coming.  Why?  Hardware designers have chosen to increase the number of processors instead of increasing the speed of a single processor.  What does this mean?  If us programmers want to be able to make use of these ever increasing number of processors, we'll need to be able to make our programs work in multi-core environments!

The easiest way to work in a multi-core environment would be to have functionality that does not have any side effects and thus could be reordered.  Hmmm, how does one do that?  Well if I had data structures that could not be mutated then those untrustworthy functions would not be able to produce side effects.  Hmmm, this sounds like immutability.

So what does immutability look like in F#?

> let foo = 5;;

val foo : int = 5

> foo <- 6="6" font="font">

  foo <- 6="6" font="font">

/home/mike/stdin(2,1): error FS0027: This value is not mutable

We cannot even reassign foo to the value of 6!  That my friends is immutability.