Home > Back-end >  Parameterized mean not working as expected
Parameterized mean not working as expected

Time:07-06

I want to run parameterized mean on a List, however it throws a compile error:

def mean[A](xs: Seq[A])(implicit num: Numeric[A]): Option[A] = {
    import num._
    if (xs.isEmpty) None
    else Some(xs.sum / xs.size)
}

cmd11.sc:4: value / is not a member of type parameter A
    else Some(xs.sum / xs.size)
                     ^Compilation Failed

What's wrong with this approach?

CodePudding user response:

Scala's numerical hierarchy resembles that of Haskell in a lot of places. In particular, Numeric does not support division, since there are plenty of useful types that can be added and multiplied but not divided (matrices being a prime example).

You're looking for Fractional. You'll also need to convert xs.size (which is an Int) to your generic type A, which can be done with Fractional.fromInt.

def mean[A](xs: Seq[A])(implicit num: Fractional[A]): Option[A] = {
    import num._
    if (xs.isEmpty) None
    else Some(xs.sum / fromInt(xs.size))
}
  • Related