Sembra che non ci sono al forno in soluzione in elisir. Così ho arrotolato il mio.
defmodule Maybe do
def and_then(nil, _), do: nil
def and_then(val,fnc), do: fnc.(val)
def and_get(struct, key), do: struct |> and_then(&(Map.get(&1, key)))
end
no_user = nil
without_contact_info = %{contact_info: nil}
with_contact_info = %{contact_info: %{address: "here"}}
no_user |> Maybe.and_then(&(Map.get(&1, :contact_info))) |> Maybe.and_then(&(Map.get(&1, :address)))
#> nil
without_contact_info |> Maybe.and_then(&(Map.get(&1, :contact_info))) |> Maybe.and_then(&(Map.get(&1, :address)))
#> nil
with_contact_info |> Maybe.and_then(&(Map.get(&1, :contact_info))) |> Maybe.and_then(&(Map.get(&1, :address)))
#> "here"
# or with the less generic `and_get`
with_contact_info |> Maybe.and_get(:contact_info) |> Maybe.and_get(:address)
#> "here"
Probabilmente non è un elisir idiomatico, ma pulisce il mio codice.
Penso che si può semplicemente utilizzare il pattern matching per gestire le situazioni in cui non c'è e non c'è 'phone_number' – JustMichael
@JustMichael È dovrebbe fare una risposta, in quanto è la soluzione migliore. –