Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increasing integer during a loop

Tags:

loops

elixir

I'm trying to increase a variable only during certain conditions

Enum.reduce(items, 0, fn item, acc  ->
  if item.condition do
    acc = acc+1
    Logger.info acc
  end
end)

But i get

** (ArithmeticError) bad argument in arithmetic expression
like image 608
icra Avatar asked Feb 17 '26 10:02

icra


1 Answers

The result returned by the function is used as the accumulator for the next iteration, recursively.

Logger.info returns :ok so you probably don't want that to be your last line.

You must also return acc if the condition doesn't meets.

Try with:

Enum.reduce(items, 0, fn item, acc  ->
  if item.condition, do: acc + 1, else: acc
end)
like image 52
Nicolas Garnil Avatar answered Feb 20 '26 04:02

Nicolas Garnil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!