Breakout of Enum.each (or equivalent)

Hi All.

I want to process each member of a list until one of those members meets a certain criteria. I appreciate that Enum.each probably isn’t the right function but I wondered if there was equivalent of a while loop with break?

cheers

Dave

1 Like

what is the problem you are solving?

look at Enum.find - or perhaps reduce_while or take_while https://hexdocs.pm/elixir/Enum.html#reduce_while/3

2 Likes

The closest thing to an imperative while loop with break is Enum.reduce_while. A more idiomatic approach would be using Stream.take_while as in

list
|> Stream.take_while(&continue_processing?/1)
|> Enum.map(...)

Or the same thing using the for expression:

for item <- Stream.take_while(list, &continue_processing?/1) do
  ...
end
3 Likes

Thanks - reduce_while is exactly what I’m looking for.

4 Likes