Immutable variable isnt immutable

Hi all,
İ started to learn elixir so that i am new for functional programing. I wonder one thing. Elixir does immutable everything. But I try some examples.
def boxes(total) do
size_50 = div(total, 50)
total = rem(total, 50)
{“big: #{size_50} total: #{total}”}
end
I created named function and i get one input. But i can change total variable. This dont throw error because of immutable variables. Why?

Hello and welcome,

You cannot really change the variable, but You can rebind it.

It’s an Elixir compromise, that You won’t find in Erlang.

Under the hood it’s doing total_0, total_1, total_2 etc.

Please don’t forget to wrap your code with ``` to make it more readable, as in markdown :slight_smile:

BTW It’s usually a good practice to avoid intermediate variables, and use pipe |> whenever You can.

4 Likes
2 Likes

You change the contents of the variable. The variable name is just an alias for the new contents.

3 Likes

Thnak you. i will be more careful with ´´´ after now

It is backtick ```, not ´´´ :slight_smile:

I really have to be more careful :slight_smile:

2 Likes

Yes, I think the easiest way to understand is that an Elixir variable is just a reference to the data and not the data itself. C programmers can see it as a pointer to the data not the data itself. :wink: So when you do

x = {1, 2}
and then
x = {:a, :b}

you are first referring the variable x to the tuple {1, 2} and then referring x to another tuple {:a, ·b} but you have NOT modified the tuples themselves. This is where the data immutability comes in as you actually CANNOT modify the tuples, or any other data for that matter. So the {:a, :b} is always the tuple {:a, :b} for as long as it exists.

This is a problem that people coming from imperative languages often run into as it very much affects HOW you work with data.

5 Likes