3

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
2
  • And what is the problem or question? Commented Jan 23, 2018 at 22:36
  • acc is not increasing as i did, question is what's the proper way of doing this Commented Jan 23, 2018 at 22:37

1 Answer 1

6

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.