jacknorman

jacknorman

How would you explain Elixir immutability?

Hello guys,

I have a fairly simple question and cant seem to understand it.

for example we have the following code:

x = 1
x = 2
IO.puts x

since elixir is immutable, why does this print 2?
now i know that elixir doesnt make any change directly to x and in fact x = 2 is does on a copy of the variable x = 1. Then how can we get the original value for x, which is 1?

First Post!

jeroenbourgois

jeroenbourgois

Immutability does not mean that you cannot rebind values. It means you cannot reassign as in other languages.

For example:

x = 1
if some_true_value do
  x = 2
end

IO.puts x # -> will output 1.

What you did in your example is just bound the value of 2 to the variable x, thus the original value of 1 is lost.

Most Liked

hauleth

hauleth

In short, both xes in your example are different variables.

It is more like:

x@1 = 1
x@2 = 2
IO.puts(x@2)

(It will look almost exactly like that in Erlang code)

The whole pattern is called rebinding and Rust offers something similar (if that make it clearer):

let x = 1;
let x = 2;
println!("{}", x);

Just in case of Elixir you do not need the let prefix.

To show that more explicitly in Elixir you can do:

x = 1
fun = fn -> x end
x = 2

IO.inspect(x, label: :x) # => 2
IO.inspect(fun.(), label: :fun) # => 1
LostKobrakai

LostKobrakai

I’d explain (the benefits of) immutability differently:

let array = [1, 2, 3];
let reversed = array.reverse();

In JS you cannot know just from reading that piece of code if array is now equal to reversed or still the original value assigned in the first line. You’d need to familiarize yourself with the implementation of Array.prototype.reverse(). In this case reversed === array, but code like that causes/caused enough problems that there’s also a Array.prototype.toReversed() nowadays, which returns a new array instead of modifying the existing one.

In elixir you can have:

list = [1, 2, 3]
reversed = Enum.reverse(list)

No matter how Enum.reverse/1 happens to be implemented it cannot make the list variable resolve to any value other than [1, 2, 3]. Essentially immutability is equal to having pass by value everywhere and no pass by reference. That’s the model upheld by the VM.

LostKobrakai

LostKobrakai

Immutability is independent from assignments – the act of creating the relationship between variable and the value it represents. Immutability only means your values (in memory) will never be modified. It doesn not mean that the variable x will always represent the same value. Once you changed what x points to there’s no way to get the value it pointed to before (even when it might still exist in memory).

11
Post #2

Last Post!

New2Elixir

New2Elixir

Thank you very much, that is very useful.

I think you hit the nail on the head with the modular function based code. Its not entirely clear ATM, however it does seem as though FP like this does seem to have the potential to make some things simpler.
Appreciate the info.

Where Next?

Popular in Questions Top

New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 131117 1222
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 44778 311
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New

We're in Beta

About us Mission Statement