Calculating product of a list of doubles

Hi all,

I see this implementation of products of a list of doubles. I don’t understand why the second case is needed. Is the implementation wrong?

def product(ds: List[Double]): Double = ds match {
    case Nil => 1.0
    case Cons(0.0, _) => 0.0
    case Cons(x,xs) => x * product(xs)
  }

As you saw the second case is not needed. But it can speed things up a lot - as soon as we see a 0 we know that the product is 0.

regards,
Siddhartha

1 Like

Ahhhh I see why now, thanks

I’d say it’s wrong.

Apparently, it is an attempt at optimization based on the assumption that if one number is 0.0, then the product is 0.0 and we can ignore the rest. However, if the List contains NaN, PositiveInfinity or NegativeInfinity, the product would be NaN, not 0.0. Unless someone wanted to redefine what the product of a list of Doubles means.

1 Like