Elixir Pattern Matching with Variables
Let's say you have a variable that you want to pattern match.
By default Elixir won't use the variable's value to do the pattern matching and it will do a regular assignment, overriding the original variable's value:
iex(1)> year = 2020
2020
iex(2)> car = %{year: 2019}
%{year: 2019}
iex(3)> %{year: year} = car
%{year: 2019}
iex(4)> year
2019
Elixir has the pin opertator ^
that does exactly what we need. So in our example we can use the pin operator and if it doesn't match you get an error:
iex(1)> year = 2020
2020
iex(2)> car = %{year: 2019}
%{year: 2019}
iex(3)> %{year: ^year} = car
** (MatchError) no match of right hand side value: %{year: 2019}
Tweet