Enum accumulator not using its start value

Hi everyone,

Can someone help me out wit the following issue? I am trying to use the Enum.reduce function as follows:

  Enum.reduce(items, Decimal.new(0), fn(i, acc) ->
  if i.tax == false do
      Decimal.mult(Decimal.new(i.qty), Decimal.new(i.unit_price))
      |> Decimal.add(Decimal.new(acc))
  end
end)

The problem is that the acc is “nil” so the add function returns error because it was un able to convert “nil” to decimal.

Any suggestions why is the accumulator not been initialized to 0.

Thanks.

1 Like

The acc definitely is initialized to 0, the issue is: what happens if i.tax is not equal to false? Well, your if condition fails, and then returns nil. THEN the next time around your accumulator is nil. You need an else clause.

1 Like

Oh… Totally true… sorry for the question. :blush:

1 Like

No problem! Glad we could get you squared away.

3 Likes

Don’t be. :slight_smile:

3 Likes