[erlang-questions] maps: pattern-match absent key?

Daniel Goertzen daniel.goertzen@REDACTED
Wed Feb 19 16:32:12 CET 2014


Is there any possibility of getting maps:is_key() as a guard so missing
keys can be detected more directly?

Consider this case of filling defaults into a map before the final clause
processes it:


myfun(M) when not is_key(abc, M) ->
  myfun(M#{abc=>123});

myfun(M) when not is_key(def, M) ->
  myfun(M#{def=>456});

myfun(M) when not is_key(pqr, M) ->
  myfun(M#{abc=>789});

myfun(#{abc:=ABC, def:=DEF, pqr:=PQR}) ->
  do_stuff.


I can't see how fail clauses could scale up to something like this.  Now
there are certainly other ways of solving the above problem (lists:foldl
comes to mind), but I still think having is_key() as a guard would be
valuable in certain situations.  It feels about as useful as...

f(X) when X/=123 ->  do_stuff.

... which I don't do often, but it is good to know it is there when I need
it.


Dan.
PS.  I accidentally posted the original question to erlang-patches, moving
to erlang-questions.


On Tue, Feb 18, 2014 at 2:23 PM, Björn-Egil Dahlberg <
wallentin.dahlberg@REDACTED> wrote:

> Yes, with fail clauses.
>
> f(#{ a := _ }) -> {a,present};
> f(_) -> {a,absent}.
>
>
>
> 2014-02-18 20:55 GMT+01:00 Daniel Goertzen <daniel.goertzen@REDACTED>:
>
>> Is there a way to pattern-match the absence of a key in a map?
>>
>> Dan.
>>
>> _______________________________________________
>> erlang-patches mailing list
>> erlang-patches@REDACTED
>> http://erlang.org/mailman/listinfo/erlang-patches
>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20140219/fddcbbe8/attachment.htm>


More information about the erlang-questions mailing list