Writing a generic mean function in Scala

前端 未结 4 1484
轮回少年
轮回少年 2020-12-14 22:41

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         


        
4条回答
  •  抹茶落季
    2020-12-14 23:37

    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.

提交回复
热议问题