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

Martin Koroudjiev mrtndimitrov@REDACTED
Thu Oct 29 17:57:19 CET 2015


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
> <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