When you have a list of values and want to reduce all of them to a single value, applying some kind of operation. You need a fold
, the most common one would be a foldLeft
.
As you can see in the scaladoc. This method receives an initial value and a combination function.
It should be obvious that the initial value should be a zero
. And that the combination function should take the current accumulate and add to it the price of the current jeans.
Nevertheless, now we have another problem, the jeans may or may not exists, thus we use option. In this case we need a way to say if they exists give me their price, if not give a default value (which in this case makes sense to be another zero
).
And that is precisely what Option.fold
give us.
Thus we end with something like:
val sum = input.foldLeft(0) {
(acc, person) =>
acc + person.jeans.fold(ifEmpty = 0)(_.price)
}
Now that you need the average, you only need to divide that sum with the count.
However, we can do the count in the same foldLeft
, just to avoid an extra iteration.
(I changed the return type, as well as the price
property, to Double to ensure accurate results).
def avgPriceJeans(input: List[Person]): Double = {
val (sum, count) = input.foldLeft((0.0d, 0)) {
case ((accSum, accCount), person) =>
(
accSum + person.jeans.fold(ifEmpty = 0.0d)(_.price),
accCount + 1
)
}
sum / count
}