I ran into this today, here’s the pattern I ended up with:
iex> Enum.reduce_while([[1, 2, 3, 4], [5, 6, 7, 8]], [], fn list, acc ->
Enum.reduce_while(list, {:cont, acc}, fn number, {:cont, acc} ->
if number < 7 do
{:cont, {:cont, [number | acc]}}
else
{:halt, {:halt, acc}}
end
end)
end)
[6, 5, 4, 3, 2, 1]
The inner :cont/:halt tuples are ultimately for consumption by the outer reduce_while, but the inner reduce_while has to pass them along to itself.
This comprehension isn’t much shorter but is less confusing:
try do
for list <- [[1, 2, 3, 4], [5, 6, 7, 8]], number <- list, reduce: [] do
acc ->
if number < 7 do
[number | acc]
else
throw acc
end
end
catch
x -> x
end






















