Reputation: 2254
I'm in the process of learning Elixir and I was curious why the following occurs:
iex(4)> case {:one, :two} do
...(4)> {:four, :five} ->
...(4)> "This won't match"
...(4)> {:one, x} ->
...(4)> "This will match and bind `x` to `:two`"
...(4)> _ ->
...(4)> "This will match any value"
...(4)> end
"This will match and bind `x` to `:two`"
So if in this 'Pattern Matching' example, why does the empty variable x
automatically bind to the atom :two
and provide a positive match? x
doesn't equal :two
when this case
is first run.
I'm just not grasping what exactly is going on.
Thanks.
Upvotes: 1
Views: 166
Reputation: 14042
Pattern matching in a clause (case or function) performs the same operation as {:one, x} = {:one, :two}
(which is also pattern matching). In this second case it is obvious that you want to test if the 2 expressions match, and you want to bind the variable x if it was unbound previously. The only difference is that if the match fails in a clause (for example {:four, :five} = {:one, :two}
) , it will try the next clause if any previous clause is throwing an exception.
It is a very powerful feature because it does a lot of operations with very few lines and keeps the code easy to read.
Upvotes: 6
Reputation: 410672
x
doesn't equal:two
when this case is first run.
Exactly. x
is an unbound variable, so it can match against anything (and will then be bound to what it matched). In this case, {:one, x}
successfully matches {:one, :two}
(since x
can match anything), and since x
was unbound, it can now be bound to :two
.
Upvotes: 3