We can match arguments like this in elixir:
iex(1)> f = fn(a, [b: a]) -> a end
#Function<12.99386804/2 in :erl_eval.expr/5>
iex(2)> f.(:me, b: :me)
:me
iex(3)> f.(:me, a: :me)
** (FunctionClauseError)
We can even match on keys of Keywords:
iex(3)> f = fn(a, [{a, a}]) -> a end
#Function<12.99386804/2 in :erl_eval.expr/5>
iex(4)> f.(:me, me: :me)
:me
iex(5)> f.(:me, mee: :me)
** (FunctionClauseError)
However we cannot match on keys in Maps:
iex(5)> f = fn(a, %{a => a}) -> a end
** (CompileError) iex:5: illegal use of variable a inside map key match, maps can only match on existing variables by using ^a
(stdlib) lists.erl:1354: :lists.mapfoldl/3
(stdlib) lists.erl:1354: :lists.mapfoldl/3
(stdlib) lists.erl:1355: :lists.mapfoldl/3
- Is there a way to match on keys in Maps?
- Why can we do it with Keywords but not with Maps?