我正在尝试在 Scala 中编写一个百分位实用程序。我正在考虑编写一个用可变数量的Int参数初始化的类。例如,一个用Percentile初始化的类50,95意味着它可以计算第 50 个百分位数和第 95 个百分位数。该类大致如下所示:
class PercentileUtil(num: Int*) {
def collect(value: Int) {
// Adds to a list
}
def compute = {
// Returns the 50th and 95th percentiles as a tuple
}
}
Run Code Online (Sandbox Code Playgroud)
我应该如何定义函数计算?
如果我是你,我会返回一张地图:
class PercentileUtil(percentiles: Int*) {
private def nthPercentile[T](n: Int, xs: Seq[T]): Seq[T] = ...
def compute[T](xs: Seq[T]) = percentiles.map(p => p -> nthPercentile(p, xs)).toMap
}
Run Code Online (Sandbox Code Playgroud)