Playing With Fire

Exploring the web one Elixir at a time

Elixir Variables

Following on from my previous post: What is this Elixir anyway? you should already have Elixir and Iex installed.

In your iex, do the following:

iex(1)> my_var = ‘thing’

There you are, your first Elixir variable. Exciting, isn’t it?

At this point, you are fully entitled to ask: ‘Is that it?’

And the answer is kinda yes but really no. Elixir variables are slightly different to what you might be used to in other languages. If you are coming from the standpoint of an imperative language you would be forgiven in thinking that this is an assignment, but it isn’t.

‘=‘ in Elixir is not an assignment operator, in fact assignment doesn’t actually exist. In Elixir, like in Erlang, this is a pattern-match operator.

Woah, what? No assignment, so how does that work then?

What happens is this: when Elixir sees the ‘=‘ operator it checks to see if the patterns used on both sides of the operator match and then if they do, bind the variables on the LHS to the values on the RHS. This way Elixir can compose and decompose patterns. If a variable has not been seen before, then it is unbound and will be bound to ensure that both sides match. This is binding the variable.

So the above expression is a match and a bind.

At this point I would just like to mention variable naming rules. They’re not overly complicated and are basically as follows:

they start with either a lower case letter or an underscore (_) they are 1 or more charaters long and can contain letters, numbers and underscore they cannot be keywords

There are however two caveats to this, the first being that a variable called _ is never bound to a value and is ignored in a match and a variable that starts with _ (i.e. _var) is bound to a value in a match, but should the value not be used then it is ignored, as in the compiler doesn’t flag it as an unused variable. More on this later.

Variable binding is such that a variable can only be bound to a value once in any match, as opposed to Erlang where a variable can only be bound once in any single context.

This means that:

iex(1)> [a,a]=[1,1]
[1, 1]
iex(2)> [a,a]=[2,2]
[2, 2]

is a valid match, whereas

iex(3)> [a,a]=[1,2]
** (MatchError) no match of right hand side value: [1, 2]

is not.

As ‘=‘ is a pattern-matching operation, the following is also quite legal:

iex(3)> a = 1
iex(4)> 1 = a
iex(5)> a

Coming from imperative languages, 1 = a might be counter-intuitive, but as Elixir makes sure that both sides match, then this is not a surprising result.

Ok, so variables are bound as the result of pattern-matching, so what about types?

Thats covered in the next post.