variable binding syntax - pattern matching in case clauses...

The following snippet is from “Programming Elixir 1.6”

​defmodule Users do
  dave = %{ name: "Dave", state: "TX", likes: "programming" }
  case dave do
    %{state: some_state} = person ->
      IO.puts "#{} lives in #{some_state}"
    _ ->
      IO.puts "No matches"

I understand how the pattern matching works… My question is about the person variable… I played with the snippet - and understand that it binds to the variable dave - and yes - the match is successful when the key state matches…
However the person -> ... syntax is a bit baffling - could someone point me to the documentation? I think I understand what is happening - just never found the documentation for the same…

Hey @atul, the syntax for matching to the left of -> is the same for the syntax matching to the left of =.

iex(1)> dave = %{ name: "Dave", state: "TX", likes: "programming" }
%{likes: "programming", name: "Dave", state: "TX"}
iex(2)> (%{state: some_state} = person) = dave
%{likes: "programming", name: "Dave", state: "TX"}
iex(3)> person
%{likes: "programming", name: "Dave", state: "TX"}
iex(4)> some_state

Thanks so much @benwilson512 - for the awesome clarification!
Amazed at how fast the question was answered! You guys rock!

I am actually surprised that this works, as I would expect it to fail with information that person is unknown binding as = is right associative.

1 Like

It’s precisely because = is right associative that this works. The right most = establishes a match context on the left, and a value on the right. Then any further = to the left work precisely as they do in any other match context.

1 Like