3 ms·
> Elixir has no early returns It's true there are few in the standard library, but look at 'Enum.reduce_while/3'. Use of throw/catch for prompt return is poss
by mikhailfranco 3y ago
> Elixir has no early returns
It's true there are few in the standard library, but look at 'Enum.reduce_while/3'.
Use of throw/catch for prompt return is possible, but is not considered good style, except perhaps if the recursion is very deep, or through an intermediate library layer that does not support prompt returns.
However, it's trivial to write your own prompt returns. It is a standard idiom (esp. in Erlang) to write a function as:
1. Public head, argument tests in guards, immediately call internal private implementation function, with additional empty accumulator argument.
2. Private function (clause 1), continuation case, does the work, then decides whether to: increment accumulator (often O1 prepending head to linked list) and recurse; or prompt return of some result, like found search, or error when some condition exceeded.
3. Private function (clause 2), termination case, empty arguments, reached the end of inputs, just return accumulator, often Enum.reverse of a list.
For example, specialized version of Enum.reduce_while over a list might be implemented as:
def foo(xs) when is_list(xs), do: do_foo(xs, [])
defp do_foo([x|xs], out) do
case bar(x) do
{:ok, val} -> do_foo(xs, [val|out])
:error -> :error
end
end
defp do_foo([], out), do: {:ok, Enum.reverse(out)}
I think when you grok this simple pattern, you will never use, Enum map, filter, reduce, reduce_while, flat_map, .... ever again, because it can emulate all of them.