In Elixir data is like a rose

“A rose by another name would smell as sweet” – Juliet (to Romeo), William Shakespeare’s Romeo and Juliet.

Dear Reader,

Elixir is described as a functional programming language with immutable data but somehow you can rebind the values to a variable. Why is this and how can the data still be called immutable? Let’s start with how it is done.

When we create a variable and assign it a value the computer does two things – it allocates a space of memory to save the value and returns an address to this memory space. We often associate these two operations in the word “variable” i.e. a memory space and its address. In Elixir the value at that memory space never changes but we can reassign the label to a new memory space.

Why it’s done this way can be shown by example.

# pretending we can't change the data at all...
age = 12
# ...to add one we need a new variable
old = add_one(age) #=> 13
older = add_one(age) #=> 14

This is OK but it can be quite verbose because we need a new label each time we transform the data. To avoid this pattern, and for your convenience, Elixir makes a new copy of the data and rebinds the label in one step.

# new copy, same label
age = 12
age = add_one(age) #=> 13

Immutable data is an advantage because it prevents processes that change data competing for the same memory spaces. This competition can causes data corruption, deadlocks and other issues that can be difficult to find and fix.

Sincerely,

Peter

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s