Elixir bits: Notes and Basic Syntax

Andrew Anderson
2 min readJan 12, 2016

--

Because spaceships.

Elixir 1.2 has been released and so has a beta version of Dave Thomas’ book Programming Elixir. I’m taking the opportunity to read a new book and play with a new language all at once. Functional programming? I’m here for you!

Anyway, these are my notes from reading the book and fiddling. Enjoy!

Repeat it with me: the equals sign is not assignment, but equality. Think math, not Java! This means that if Elixir can find a way of making one side equal with the other, it will.

a = 5
5 = a
4 = a # returns error

Multiple assignment is supported and highly encouraged:

[a, b, c] = [1, 2, [3, 4, 5]]
1 = a
2 = b
[3,4,5] = c

Programming is about transforming data from one form (unusable or raw) to another form (exactly what we need). FP focuses on data transformation rather than data modeling.

Immutability performance doesn’t stink because guess what: values are immutable. Therefore:

arr = [1, 2, 3]
arr2 = [ 0 | arr]

arr[0] and arr2[1] point to the same memory location because neither can ever change!!!!

So much fun.

Once you accept the concept, coding with immutable data is surprisingly easy. You just have to remember that any function that transforms data will return a new copy of it.

one_million = 1_000_000
# Underscores can appear in decimal numbers
one_thousand = 1_000.00
# And in floats.

Regex syntax looks like it has a nice delimiter setup:

regex = ~r{a}
Regex.scan regex, "atomized"

{} indicate tuples, handshake maximum of four elements.

Atoms are cool and are somewhat like Ruby symbols. They typically point to things. They can be used in pattern matching, and common idiom is to return an atom to indicate function status:

{status, file} = File.open('a-file.txt')
:ok = status

This makes it easy to throw an error when a function fails (another idiom):

{:ok, file} = File.open('non-existent-file')
** (MatchError) no match of right hand side value: {:error, :enoent}

And that’s going to do it for tonight! More to process on the basic language syntax, but it’s a start.

--

--

Andrew Anderson

Geek, husband, father, and Christian. Not necessarily in that order.