How to do pattern matching on map keys in function heads in elixir -
i can't seem find way pattern match on map's key in function head. there way this? i'm trying run different code depending on whether key exists in map or not (and wanted avoid if/else , like)
this code looks like
def my_func(key, %{key => _} = map), do: ...
which gives me error
** (compileerror) illegal use of variable key inside map key match, maps can match on existing variable using ^key
of course tried using ^
def my_func(key, %{^key => _} = map), do: ...
which gives
** (compileerror) unbound variable ^key
i'm using elixir 1.3.1/erlang 19.0 x64 on windows 8.1 machine. reading!
just pattern match key need:
defmodule test def my_func(%{"a" => value}), do: {:a, value} def my_func(%{"b" => value}), do: {:b, value} def my_func(_), do: :error end
then in iex:
iex(1)> test.my_func(%{"a" => 1}) {:a, 1} iex(2)> test.my_func(%{"b" => 2}) {:b, 2}
also order of clauses important. example if trying match %{"b" => 2}
have following map %{"a" => 1, "b" => 2}
, key "a"
match first, because in first clause:
iex(3)> test.my_func(%{"a" => 1, "b" => 2}) {:a, 1}
if want generate every key can match recommend different approach. example, if want map function keys:
defmodule test0 def my_op({"times_2", value}), do: {"times_2", value * 2} def my_op({"times_3", value}), do: {"times_3", value * 3} def my_op({key, value}), do: {key, value} def my_func(m) enum.map(m, &my_op/1) |> enum.into(%{}) end end
so following:
iex(1)> test0.my_func(%{"times_2" => 2, "times_3" => 3, "whatever" => 42}) %{"times_2" => 4, "times_3" => 9, "whatever" => 42}
update according comments answer
you cannot pattern match key variable. problem compiler needs generate code search doesn't know yet. when pattern match give compiler hints of it'll receive. keys in maps hint key itself. in case, pointing first argument should key for, not enough compiler. approach should use if statement:
defmodule test2 def my_func(k, m) if map.haskey?(k, m), do: warning(k, m), else: foo(k, m) end def warning(k, m) #warning m end # in function apply pattern matching # described in first part of answer. def foo(k, m) value = # %{m | key => value} end end
i hope answers question.
Comments
Post a Comment