Kotaa
Kotaa

Reputation: 201

Enum.reduce returns a model instead of a number

In my model I have this:

  # ....
  def total_price(self) do
    Enum.reduce(self.child_items, fn(x, acc) ->
      x.price + acc
    end)
  end

It returns a ChildItem instead of a number representing the total price. Why is that and how to fix that?

Upvotes: 1

Views: 68

Answers (1)

nietaki
nietaki

Reputation: 9018

Enum.reduce has two versions: reduce/2 and reduce/3. The one which takes 2 arguments takes first element in your collection as the initial accumulator - in your case the first ChildItem.

What you want to do is provide the initial cost 0 as the accumulator yourself:

  def total_price(self) do
    Enum.reduce(self.child_items, 0, fn(x, acc) ->
      x.price + acc
    end)
  end

Upvotes: 2

Related Questions