Assignment:
I Do Not Think It Means What You Think It Means.

Let’s use the interactive Elixir shell, IEx, to look at a simple piece of code. (Remember, you start IEx at the command prompt using the iex command. You enter Elixir code at its iex> prompt, and it displays the resulting values.)

 iex>​ a = 1
 1
 iex>​ a + 3
 4

Most programmers would look at this code and say, “OK, we assign 1 to a variable a, then on the next line we add 3 to a, giving us 4.”

But when it comes to Elixir, they’d be wrong. In Elixir, the equals sign is not an assignment. Instead it’s like an assertion. It succeeds if Elixir can find a way of making the left-hand side equal the right-hand side. Elixir calls the = symbol the match operator.

In this case, the left-hand side is a variable and the right-hand side is an integer literal, so Elixir can make the match true by binding the variable a to value 1. You could argue it is just an assignment. But let’s take it up a notch.

 iex>​ a = 1
 1
 iex>​ 1 = a
 1
 iex>​ 2 = a
 **​ (MatchError) no match of right hand side value: 1

Look at the second line of code, 1 = a. It’s another match, and it passes. The variable a already has the value 1 (it was set in the first line), so what’s on the left of the equals sign is the same as what’s on the right, and the match succeeds.

But the third line, 2 = a, raises an error. You might have expected it to assign 2 to a, as that would make the match succeed, but Elixir will only change the value of a variable on the left side of an equals sign—on the right a variable is replaced with its value. This failing line of code is the same as 2 = 1, which causes the error.