What's the most idiomatic way to require a key in a keyword list or make it optional

nil is a Value. In some cases (by convention or agreement) nil is used to represent the absence of a value - but in some domains nil could have an entirely different meaning.

In this context the standalone pattern of %{a:, _} will match the “presence of any value (including nil) under the key :a” - so any match subsequent to that pattern implies the absence of the key :a in the map.

Ultimately that is why one has to be careful when using Map.get/3 - by relying on the default, a return value of nil could indicate the absence of the key or that nil was stored under the key (which is why an alternate default can be specified).

It is for this reason that Erlang doesn’t use nil (though :undefined is used when something cannot be found/doesn’t exist).

1 Like