Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I break out of a Enum.reduce in elixir

Tags:

erlang

elixir

I want to find the sum of all positive number that come before first negative number.

I got the following list in elixir.

iex(4)> steps = [0,1,2,3,-4,5,6,-1]

And I calculate the sum of this list as follows

Enum.reduce(steps,0,fn x,acc -> acc=acc+x end)

How to come out of reduce once we hit a negative number?

like image 786
arun dhyani Avatar asked Sep 20 '18 19:09

arun dhyani


2 Answers

Using Enum.reduce_while https://hexdocs.pm/elixir/Enum.html#reduce_while/3

[1,2,3,-4,5,6,-1] |> Enum.reduce_while(0, fn x, acc ->
   if x > 0, do: {:cont, acc + x}, else: {:halt, acc}
end )
like image 73
GavinBrelstaff Avatar answered Nov 14 '22 21:11

GavinBrelstaff


You can use Enum.take_while/2

Takes the items from the beginning of the enumerable while fun returns a truthy value.

Enum.take_while([0, 1, 2, 3, -4, 5, 6, -1], fn(x) -> x >= 0 end) |> Enum.sum

=> 6

Or use the shorthand

list = [0, 1, 2, 3, -4, 5, 6, -1]
Enum.take_while(list, &(&1 >= 0)) |> Enum.sum
like image 11
Bitwise Avatar answered Nov 14 '22 22:11

Bitwise