0

I am new for function language. i practised some thing but i wonder one thing. Elixir says me that everything is immutable but i can change variable in elixir. Is there something that I dont know about it? My example is

defmodule Practise do
    def boxes(total) do
        size_50 = div(total, 50)
        total = rem(total, 50)  
        {"big: #{size_50} total: #{total}"}
    end
end

I can change total variable with new value in same named function. So that i think it is immutable. Is it correct?

1 Answers1

0

Reusing variable names (which is often referred to as rebinding) is just a convenience in Elixir - it's equivalent to using a temporary variable but with the same name. The reference to your original total gets lost in the scope of the function Practice.boxes. But that doesn't matter to you since you don't need it again - you just need the new one.

This is a rare concession made by the designers of Elixir towards imperative programming. Indeed, an expression such as x = x + 1 might be mistaken for pattern matching phrase.

GavinBrelstaff
  • 3,016
  • 2
  • 21
  • 39
  • Thank you it is more clear now. But i wonder one thing too. function is mathematical logic. We can think it with math. x = x + 3 is impossible for math(e.g. 2 = 2 + 3). But we can do it with elixir. what is the reason of this? – Yusuf Yalcin Mar 29 '21 at 12:10
  • Also is rebind variable not mutating? when we rebinf variable then it has new value. that means mutable. am i wrong? – Yusuf Yalcin Mar 29 '21 at 14:29
  • 1
    Here is an answer to _why_ from José Valim, the creator of the language: http://blog.plataformatec.com.br/2016/01/comparing-elixir-and-erlang-variables/ – Aleksei Matiushkin Mar 29 '21 at 16:54
  • @YusufYalcin I've add a short paragraph in response to your reply – GavinBrelstaff Mar 29 '21 at 17:34
  • @GavinBrelstaff Thank you for your answer.. it is good explanation for me – Yusuf Yalcin Mar 29 '21 at 18:01