[erlang-questions] pattern matching with maps in function heads

Alex Shneyderman a.shneyderman@REDACTED
Thu Oct 29 17:21:34 CET 2015


Attr might have multiple values.

io:format("b: ~p~n", maps:get(b, M)),
io:format("d: ~p~n", maps:get(d, M)).

is probably what you want.

It is discussed briefly in LYSE book:

"You also cannot do matching of a key by value (#{X := val} = Map)
because there could be multiple keys with the same value."

Cheers,
Alex.

On Thu, Oct 29, 2015 at 11:33 AM, Martin Koroudjiev
<mrtndimitrov@REDACTED> wrote:
> Hello,
>
> How can I do pattern matching with maps in function heads? I tried
>
> -module(m1).
>
> -export([main/0]).
>
> main() ->
>     M = #{a => 1, b => 2, c => 3},
>     io:format("b: ~p~n", get_attr(b, M)),
>     io:format("d: ~p~n", get_attr(d, M)).
>
> get_attr(Attr, #{Attr := Val} = Map) ->
>     Val;
> get_attr(_Attr, _M) ->
>     not_found.
>
> but I get compile error: m1.erl:10: variable 'Attr' is unbound
>
> Thanks in advance,
> Martin
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions



More information about the erlang-questions mailing list