Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "immutable variable" mean in functional programming?

I'm new to functional programming, and I don't understand the concept of immutability; e.g. an immutable variable.

For example, in Standard ML (SML):

val a = 3
val a = a + 1

The second line does not "change" the value of variable a; however, afterwards, a equals 4. Can someone please explain this?

Also, what is the benefit of "no mutation" (immutability)?

like image 962
nzomkxia Avatar asked Mar 27 '13 07:03

nzomkxia


1 Answers

When we say a variable is immutable, we mean that its own value cannot be changed. What you're showing there with

val a = 3
val a = a+1

is: the new value of a is simply "shadowing" the old value of a. a is just a name that is bound to 3, and in the second line, it's bound to 4. The old value of a still exists, it's just inaccessible.

This can be seen more apparently if you're using some sort of data structures. There's no mutator methods like you see in many other languages. For example, if you have a list val L = [1,2,3], then there's no way to change the first value in L. You would have to shadow L altogether, and create a new list to shadow the old one.

So, every time you bind a new value declaration it creates a new environment with all the current name/value bindings. None of these bindings can be changed, they're simply shadowed.

like image 118
AAA Avatar answered Nov 15 '22 08:11

AAA