It seems that there are no baked in solution in Elixir. So I rolled up my own.
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"
It's probably not idiomatic Elixir however it cleans up my code.
phone_number
– NoDisplayName Mar 14 '16 at 3:47