2012-07-13 123 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)