[Proposal] 💥 pop!

68 views
Skip to first unread message

Christopher Keele

unread,
Nov 10, 2017, 11:58:28 AM11/10/17
to elixir-lang-core
I often want to extract a mandatory value from an options keyword list, and continue treating the rest as less strict configuration.

This is a two-liner: mandatory = Keyword.fetch!(options, :mandatory); optional = Keyword.delete(options, :mandatory) 

I do this just often enough, I'd like to propose {mandatory, optional} = Keyword.pop!(options, :mandatory)
  • It fits in well with the current Map API
  • It's simple to implement and maintain
  • It provides an analog for the keyword variant of the (non-existent) positional def foo(mandatory, *optional)
However it merely replaces a trivial two-liner, so this comes down to others in core finding the idiom common enough to merit widening the Map API surface area. I do, hence the proposal, but I'd love to hear other's experiences.

OvermindDL1

unread,
Nov 13, 2017, 12:58:22 PM11/13/17
to elixir-lang-core
You could just do something like (not perfectly efficient, but good enough for most, and it lets the options be passed in as a list or map or any acceptable enumeration):

```elixir
options = Map.merge(%{this_has_a_default: 42}, Enum.into(options, %{}))
options.this_is_required # Throws if use did not define
options.this_has_a_default # Uses the default value specified above if the user did not specify it
options[:this_is_optional] # Returns null if the user did not define it
```

I have an erlang version that works on full property lists that is a lot more efficient and can even prevent 'unknown' values from being passed in too.  I posted an Elixir'ified version of it on the forums a little bit back.
Reply all
Reply to author
Forward
0 new messages