1

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.

reknirt
  • 2,237
  • 5
  • 29
  • 48

2 Answers2

6

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.

Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168
Pascal
  • 13,977
  • 2
  • 24
  • 32
  • If you want to use the current value of x to pattern match against, use can use the pin operator: ^x http://stackoverflow.com/questions/27971357/what-is-the-pin-operator-for-and-are-elixir-variables-mutable – ibizaman Nov 24 '15 at 10:21
3

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.

mipadi
  • 398,885
  • 90
  • 523
  • 479
  • I guess that makes sense. But I'm still wondering what causes `x` to bind to `:two:`? I understand that it can, but why is it necessary that it does? `x` could just remain an empty variable that doesn't match `:two`, could it not? – reknirt Feb 28 '15 at 03:29
  • @reknirt: Do you mean, why is it necessary to bind variables to values in the first place? – mipadi Feb 28 '15 at 06:03
  • Was looking back through this and I'd love for you to explain why it is indeed necessary to bind variables to values in the first place. – reknirt Jun 18 '15 at 17:57