Skip to content

Instantly share code, notes, and snippets.

@bmitch
Last active June 17, 2017 18:38
Show Gist options
  • Save bmitch/a999822c164963671e3bdecd521f3653 to your computer and use it in GitHub Desktop.
Save bmitch/a999822c164963671e3bdecd521f3653 to your computer and use it in GitHub Desktop.
elixir-immutability.md

Back

Immutability

  • Once a variable a list such as [1, 2 ,3] you know it will always reference those same variables (until you rebind the variable).
  • What if you need to add 100 to each element in [1, 2, 3]? Elixir produces a copy of the original, containing the new values.

This uses the [ head | tail ] operator to build a new list with head as the first element and tail as the rest:

list1 = [3, 2, 1]
#[3, 2, 1]

list2 = [ 4 | list1 ]
#[4, 3, 2, 1]

In other languages list would be built by creating a new list containing a 4, a 3, a 2 and a 1. The three values in list1 would be copied onto the tail of list2 which would be needed because list1 would be mutable.

But in Elixir list1 will never change so it just constructs a new list with a head of 4 and a tail of list1.

Any function that transforms data returns a copy of it. So for example, we never capitalize a string, we return a capitialized copy of a string:

name = "elixir"
#"elixir"

cap_name = String.capitalize name
#"Elixir"

name
"elixir"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment