Skip to main content

Command Palette

Search for a command to run...

In Elixir data is like a rose

Published
2 min read
P

I build meaningful software by empathising with design, development and business needs. My interests are test automation, functional programming and full-stack web development using NodeJS and other tools.

“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

More from this blog

S

Soliloquy

26 posts

Father, husband, cosmopolitan geek and music lover. Learning how to build beautiful things.