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

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
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
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: <h1>Create Post</h1> <%= ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
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

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29377 241
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30877 112
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36128 110
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
marick
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a nov...
New

We're in Beta

About us Mission Statement