Writing a generic mean function in Scala

前端 未结 4 1495
轮回少年
轮回少年 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条回答
  •  旧时难觅i
    2020-12-14 23:22

    One of your version is pretty close:

    def mean[T](xs: Iterable[T])(implicit num: Numeric[T]):Double = 
      num.toDouble(xs.sum) / xs.size
    

    Here is the other syntax:

    def mean[T: Numeric](xs: Iterable[T]):Double =
      implicitly[Numeric[T]].toDouble(xs.sum) / xs.size
    

提交回复
热议问题