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)?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With