2012-07-13 122 views
1

我试着在Scala写一个百分数实用程序。我正在考虑编写一个用可变数量的int参数初始化的类。例如,用50,95初始化的百分等级意味着它可以计算第50和第95百分位数。该类将大致是这样的可变元素数返回元组

class PercentileUtil(num:Int*){ def collect(value:Int){// Add to a list} def compute = { //returns the 50th and 95th percentiles as a tuple }

如何定义函数计算?

+5

具有可变数量元素的元组听起来像是我的列表。请提供更多细节。 – 2012-07-13 18:49:09

回答

2

我会返回一个地图,如果我是你:

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 
} 
2

如果它是你可以声明的返回值是一个产品的元组。

def compute: Product = if(...) (1,2) else ("1", "2", "3") 

compute match { 
    case (a: Int, b: Int) => 
    case (a: String, b: String, c: String) => 
} 

compute.productIterator.foreach(println)