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?
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 )
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With