Idea: optional map values

Hi,

I would like to suggest an extension to the maps construction syntax to allow for the following:

#{
  key1 => Value1,
  key2 => Value2 when Guard
}

key2 would not be included in the map if the guard expression fails.

Questions

  • Would this be useful?
  • Does anyone see any problems/challenges with the above?
3 Likes

do you have any examples where this would be useful/convenient?

2 Likes

In my case it’s about building map data structures that are meant to be matched against later in the process.

It would of course be possible to include sentinel values such as undefined or null when a value is non existent, but that makes matching the said data structures much more annoying: instead of checking on #{value2 := _}, we have to do #{value2 := Value2} when Value2 =/= undefined.

1 Like

it would be more elegant, but i think same can be achieved with Eep 0058 - Erlang/OTP which is now part of OTP-26.

4 Likes

I wonder if something like that could be used to specify default values when matching.
E.g.

my_fun(#{sleep := Value default 1}) ->
    timer:sleep(Value).

Meaning, "if there is no “sleep” field in the map passed, use the default of 1. For now I tend to do:

my_fun(Opts) ->
    Value = maps:get(sleep, Opts, 1),
    timer:sleep(Value).

I know that in this case it would be possible to use pattern-matching:

my_fun(#{sleep := Value}) ->
    timer:sleep(Value);
my_fun(_) ->
    timer:sleep(1).

But it does not look elegant either, and for more complex functions it’s not an option.

2 Likes