Reputation: 11234
Playing around with Elixir. Consider this scenario. I have
iex> a = b = 1 #=> a = 1, b = 1
iex> c = true
iex> a == b #=> true
iex> true = c #=> true
Therefore I assumed the below would return true, but got illegal pattern.
iex> a == b = c
** (CompileError) ... illegal pattern
Upvotes: 1
Views: 139
Reputation: 11
When using the =
operator, you are using the match operator, which performs pattern matching and not an assignment.
The way the =
operator works is this:
pattern = expression
At runtime, the left side is matched to the right side. So, the left side is called a pattern, whereas the right side is an Elixir term expression.
Even though I would not be able to throw a formal definition of what a pattern is, I can tell you that it is not the same as an expression. As the illegal pattern
error states, there are more restrictions to what a pattern can be.
In general, a pattern can use compile-time constructs, but no runtime values. You can use base types constructors such as tuples (nested or not), lists, maps or even constants as patterns.
For instance these are valid patterns, given those variables are unbound:
{:ok, content}
[head | tail]
1
x
{:ok, { day, month, year }, { hour, minute, second} }
However, the following are runtime expressions that aren't legal patterns:
1 == 1
a + b
true != false
a == b
You can use this kind of expression on the right hand side with no problem, but not on the left hand side.
An exception to this would be the ++
and <>
operators, as they automatically translate to constructor styles (for instance "hello" <> "world"
is the same as <<"hello", "world">>
)
Upvotes: 1