--
You received this message because you are subscribed to the Google Groups "elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-co...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/616a2726-740d-4b10-a02c-2a0c4e195a2fn%40googlegroups.com.
One potential benefit to a Map.fetch/3 command that wasn't
considered is that it could help users define more specific error
types. There's a loose convention to use {:ok, val} | :error |
{:error, reason} as a "result" type in Elixir (analogous to Rust's
Option and Result or Haskell's Maybe and Either). Map.fetch/3
conforms to this by returning {:ok, val} | :error which is very
useful!
However, sometimes I want to return a more specific error from
Map.fetch failure. Consider the following case:
states = %{"AL" => "Alabama", "AK" => "Alaska", "AR" =>
"Arkansas", ... }
Map.fetch(states, abbreviation)
This will return either {:ok, name} or :error. However, for the
caller's convenience, I would return {:ok, name} or {:error,
"State not found!"}.
Map.get/2 could be used:
case Map.get(states, abbreviation) do
nil -> {:error, "State not found!"}
name -> {:ok, name}
end
or Map.fetch/2:
case Map.fetch(states, abbreviation) do
{:ok, name} -> {:ok, name}
:error -> {:error, "State not found!"}
end
But I would truly like to have a Map.fetch/3 function where the
third argument is alternate default value (a la Map.get/3)
Map.fetch(states, abbreviation, {:error, "State not found!"})
--
You received this message because you are subscribed to the Google Groups "elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-co...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/eec03b82-3c23-4d56-a930-de1077913782n%40googlegroups.com.