I\'m trying to write a generic mean function that operates on an Iterable that contains numeric types. It would operate, say, on arrays, as so:
val rand = n
This is quite an old question, but I am basically doing this
def average[A](list: List[Any])(implicit numerics: Numeric[A]): Double = {
list.map(Option(_)).filter(_.isDefined).flatten match {
case Nil => 0.0
case definedElements => numerics.toDouble(list.map(_.asInstanceOf[A]).sum) / definedElements.length.toDouble
}
}
for a list which might contain null
values (I have to keep interoperability with Java). The null
elements are not counted towards the average.