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

Peti Gömöri <>
Thu Oct 29 19:38:32 CET 2015


Hello Martin, Alex

This is interesting as this works

get_attr(Attr, Map) ->
    #{Attr := Val} = Map, Val.

It is kind of documented that only matching literal keys in function heads
are supported:
http://www.erlang.org/doc/reference_manual/expressions.html#id81375
under Matching Syntax.

I wonder how complicated it would be to support the syntax in question.


On Thu, Oct 29, 2015 at 5:57 PM, Martin Koroudjiev <>
wrote:

> Hello and thank,
>
> Yes, I know about the maps module but was trying to explore the map
> syntax and use pattern matching. I, actually, am not trying to match on
> the value but on the key name. I thought Attrib will take the value of
> the first argument and this value will be used as key name in the map.
>
> Regards,
> Martin
>
> On 10/29/2015 6:21 PM, Alex Shneyderman wrote:
> > 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
> > <> 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
> >> 
> >> http://erlang.org/mailman/listinfo/erlang-questions
>
> _______________________________________________
> erlang-questions mailing list
> 
> http://erlang.org/mailman/listinfo/erlang-questions
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20151029/6326a268/attachment.html>


More information about the erlang-questions mailing list