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

The fact I was nudging towards was that a keyword list can have multiple values for a single key.

However in 99.9% of the cases there is no intent to support multiple values per key - and nothing in the original post suggested that there was any intent to support multiple :a or :b values.

I suspect keyword lists being the default mechanism for passing options to Elixir functions motivated the choice here - not the fact that a keyword list can have multiple values for the same key.

At the same time I’m not aware of a convention that suggests which value should be given preference when an option appears multiple times in an option list - the one closest to the beginning of the list or the one closest to the end?(‡)

My choice would be to pass options in a Map to begin with but I suspect that the “option keyword list mechanism” was devised during a time where there were no Maps but only HashDicts (Edit: The reasons are actually quite different).

Again - in 99.9% of the cases the possibility of multiple values per key is a non-issue but it probably doesn’t hurt to keep this potential “gotcha” in mind.

‡ Based on José’s comment:

so

> Enum.into([a: 2, a: 3], %{a: 1})
%{a: 3}

the last value should likely be the “honoured” value (which interestingly could be the “first” value added to the list when it was created by cons-ing) if only one value is desired. However since something like for cmd_opts reverses the order of the options during validation, I guess, no definitive call can be made.

1 Like