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?

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 #3

Where Next?

Popular in Questions Top

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&query=perfume&page=2, I would like to get: ...
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
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 53690 245
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
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

We're in Beta

About us Mission Statement