Craftsman at work

I'm Artur Karbone, coding software architect and independent IT consultant and this is my blog about craftsmanship, architecture, distributive systems, management and much more.

Immutability in Elixir

In Erlang You are allowed to bind a variable only once. There is no chance to use the same variable even as an accumulator. Let's look at the code:

Price = Catalog.lookup( Item)  
Price2 = Price * Quantity  
Price3 = Price2 + Price2 * Tax  

Not perfect one in terms of readability. Right?

Let's look at its Elixir counterpart:

price = Catalog.lookup(item)  
price = price * quantity  
price = price + price * tax  

Does It look like Elixir is mutable? But only from the first sight and reall it's not.

Under the hood, the compiler is implicitly doing kind of what the original Erlang program does. The result is that, there’s no mutable state internally at all.

Here is a little prove on concept. Let's introduce price_at_the_beginning variable and make sure it does not equal to the price at the end:

price = Catalog.lookup(item)  
price_at_the_beginning = price  
price = price * quantity  
price = price + price * tax  
inspect {price, price_at_the_beginning}  
comments powered by Disqus