Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading