本文介绍了如何在 Scala 中实现通用平均函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于任何特定类型的数字,即双精度/整数,这似乎是一个简单的问题,但在一般情况下很难编写.
It seems easy problem for any specific kind of Number i.e. Double/Integer but it is hard to write in general case.
implicit def iterebleWithAvg(data:Iterable[Double]) = new {
def avg:Double = data.sum / data.size
}
如何为任何类型的 Number(Int,Float,Double,BigDecemial) 实现这个?
How to implement this for any kind of Number(Int,Float,Double,BigDecemial)?
推荐答案
你必须传递一个隐式的Numeric
,它允许求和并转换为双精度:
You have to pass an implicit Numeric
which will allow summation and conversion to Double:
def average[T]( ts: Iterable[T] )( implicit num: Numeric[T] ) = {
num.toDouble( ts.sum ) / ts.size
}
编译器会为你提供正确的实例:
The compiler will provide the correct instance for you:
scala> average( List( 1,2,3,4) )
res8: Double = 2.5
scala> average( 0.1 to 1.1 by 0.05 )
res9: Double = 0.6000000000000001
scala> average( Set( BigInt(120), BigInt(1200) ) )
res10: Double = 660.0
您可以使用该函数定义隐式视图(前提是您传播隐式数字依赖项):
You can the use the function to define an implicit view (provided you propagate the implicit numeric dependency):
implicit def iterebleWithAvg[T:Numeric](data:Iterable[T]) = new {
def avg = average(data)
}
scala> List(1,2,3,4).avg
res13: Double = 2.5
这篇关于如何在 Scala 中实现通用平均函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!