jacknorman

jacknorman

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?

Showing Posts 1 to 10

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.

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
jacknorman

jacknorman OP

the example you provided means that value of x is being changed scope wise. For example:

x = 1
if some_true_value do
  x = 2
  IO.puts x # -> will output 2.
end

IO.puts x # -> will output 1.

so like in Rust, it gives an error and also gives you the option to declare a variable mutable or immutable, should we be getting an error when we something like the code i posted?

LostKobrakai

LostKobrakai

You’ll get an error if you bind a variable, but don’t use it within the scope it’s assigned in, but not if you use it as well.

jeroenbourgois

jeroenbourgois

@jacknorman consider the response by @LostKobrakai, it is much more correct.

Another example which you might run in to when you are new to Elixir or immutabillity in general, is that you actually forget to reassign, e.g. when using lists and maps.

animals = [:bear, :elephant]
# no bears!
Enum.reject(animals, fn animal -> animal == :bear)
IO.inspect(animals) # -> [:bear, :elephant]

# so instead
animals = Enum.reject(animals, fn animal -> animal == :bear)
IO.inspect(animals) # -> [:elephant]
jacknorman

jacknorman OP

alright, so that means that values can be overwritten in elixir for variables but memory wise the values stay the same? can you please explain with an example

jacknorman

jacknorman OP

this I understand. The same concept is used when working with for loops in elixir, or when using sockets in live views and you have to do something like this for example

socket = socket |> assign()
jeroenbourgois

jeroenbourgois

Indeed. As for the example, I am no expert in Elixir either… But what I understand is that values get assigned to variables and get scoped into the block they are defined in.

So

x = 1  # variable x is created and the value 1 is assigned
x = 2  # variable x is reassigned with value 2, same memory address
if :foo == :foo do
  x = 3 # variable x is created inside if block, think of the name as x' 
end
# here x is still 2, x' from inside the if block is gone.

@LostKobrakai does that make sense?

If you wanted the value from inside the if block, you’d need to assign is:

x = 
  if :foo == :foo do
     3
  else
     4
 end

x will be 3

jacknorman

jacknorman OP

its a good answer but sadly still doesnt answer my question.

@LostKobrakai and @jeroenbourgois I think immutability means that whatever variable we are creating can be changed but when we look at it in the view of a process then their states cannot be changed once they are running. I saw this video and in this he explains that actually a copy is being made which is used but the original data stays the same.

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

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
jaybe78
Hello, I’m developing a online persistent chat system (what’s app) like using elixir/dynamodb/aws for a mobile app(flutter). The diffic...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
widianto
I think I’ve found a small improvement I could contribute to <%= web_namespace %>.CoreComponents (installer/templates/phx_web/compo...
New

Other Trending Topics Top

garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New
aseigo
ICal is a library for interacting with iCalendar data. It parses iCalendars into typed Elixir structs via ICal.from_ics, and can prepare ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews