Sergey Bushmanov
Sergey Bushmanov

Reputation: 25199

Parameterized mean not working as expected

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?

Upvotes: 1

Views: 32

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70287

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))
}

Upvotes: 4

Related Questions