Understand immutability

Hello, I’m new to Elixir, I’m reading a book called Learning Functional Programming with Elixir I’m reading a subject of how Elixir data are immutable but when I just create a value in iex shell (Elixir (1.11.0) ) like this:

message = "Hello, World!!!"

display the above variable I get what I’m expecting but what I do not understand is, if I mutate the message variable there’s not an error.

message = "Hello!!!"

displaying again message variable I get no error and the output is Hello!!!

Please help me to understand what immutability means and how it works in Elixir

What you doing is rebinding and it doesn’t break immutability. You are creating a new variable with same name that shadows the old one. This should explain it to you https://medium.com/everydayhero-engineering/elixir-variable-rebinding-342c5d0fd961

4 Likes

Thank you @wanton7

The answer from wanton7 is perfect, even though even for me it looked strange at first.

If you want to understand why immutability, the best explanation I found about immutability was Rich Hickey’s (he created Clojure and Datomic).

2 Likes

Thank you @DanBunea

It can be slightly confusing because elixir allows rebinding identifiers. Immutability is as a result a bit closer to how strings behave in many popular languages (e.g. C#) where the value a variable name points to can change but the value itself cannot.

Every change to a value results in a new value and to keep track of it you need to bind it to a name, but the name can be reused while the value itself can’t be changed.

If you consider this JavaScript example:

let person = { name: “Bob” };

Then following this in elixir you could do something conceptually similar to:

person = { name: “Nicola” };

But you couldn’t do something conceptually similar to:

person.name = “Nicola”;

However another slight difference in this comparison is in elixir everything is passed by value, nothing is passed by reference so changes to what a name points to only impacts usage of that name going forward and never any previous usage of that name.

2 Likes

Not sure if this is helpful to you but this something which is easy to miss as a beginner.

a = 1

for i <- 1..5 do
  a = a + 1
  IO.puts(" #{i}) #{a}")
end

IO.puts("After `for` #{a}")

You can compare the output for similar code in other language and see the difference.

2 Likes

Thanks @akash-akya