Hi,
I’m new to functional programming in general and to Elixir in particular. One thing I have some difficulties with is having no early return. I found This article, which works on some cases but not in one like this:
Let’s say I have 3 functions that can return either a value or nil:
get_text(:first)
get_text(:second)
get_text(:third)
I want to stop and get the result from the first function that returns a value (not nil) or nil if all fails.
Something like this works:
def test_cases() do
case get_text(:first) do
value when value != nil ->
value
nil ->
case get_text(:second) do
value when value != nil ->
value
nil ->
case get_text(:third) do
value when value != nil ->
value
nil ->
nil
end
end
end
end
but this looks really bad.
Using cond do
works too and looks nicer but require calling each function twice:
def text_cond() do
cond do
get_text(:first) != nil -> get_text(:first)
get_text(:second) != nil -> get_text(:second)
get_text(:third) != nil -> get_text(:third)
true -> nil
end
end
I’m sure I’m missing something. Any help with this?