EddTally
Pattern matching a map in function parameters
Hello, I am just wondering whether this is possible, or am I doing something wrong.
If so, what would be the best way to pattern match this type of thing, all in one function with a case statement?
def test1(%{num: num}), do: num + 1
def test1(%{num: num, acc: acc}), do: num + acciex(8)> test1(%{num: 1})
2
iex(9)> test1(%{num: 1, acc: 5})
2
I expected to receive 6 on the second function call iex(9).
Marked As Solved
kokolegorille
The order of the functions is highly important, as the first match wins…
You can switch test1 functions to make it work.
Also Liked
kokolegorille
The usual rule of thumb is to go from the more specific, to the more generic…
Of course for each rule You can find exception 
sodapopcan
It may also be helpful to clarify that maps, unlike lists, allow for partial matches, so:
%{num: num} = %{num: 1, acc: 5} # Match!
[a, b, c] = [1, 2, 3, 4] # No match!
gregvaughn
Another option is to consider 1 as a default value of acc and then you can do it with a single function clause
def test1(%{num: num} = m), do: num + Map.get(m, :acc, 1)
kokolegorille
I would say list does partial match too…
[a, b, c | rest] = [1, 2, 3, 4] # match!
gregvaughn
You can’t do that with pattern matching. You have to write the one line function that uses if and Map.get to determine and then call x or y function.







