2013-03-11 34 views
1

我開始學習斯卡拉並在閱讀斯卡拉的不耐煩了,到了以下解決方案的一個練習:函數獲取陣列和功能的元件陣列

//No function 
def positivesThenZerosAndNegatives(values: Array[Int]) = { 
    Array.concat(for (value <- values if value > 0) yield value, 
     for (value <- values if value == 0) yield value, 
     for (value <- values if value < 0) yield value) 
} 

但現在我試圖通過爲PARAM應用於過濾器上的每一個全面的功能:

//Trying to use a function (filter) 
def positivesThenZerosAndNegatives2(values: Array[Int]) = { 
    Array.concat(filter(values, _ > 0), filter(values, _ == 0), filter(values, _ < 0)) 
} 

def filter[T: Int](values: Array[T], f: (T) => Boolean) = { 
    for (value <- values if f(value)) yield value 
} 

我還沒有找到引用的元件陣列的正確途徑。

回答

3

你可以寫你的filter方法如下:

import scala.reflect.ClassTag 

def filter[T: ClassTag](values: Array[T], f: T => Boolean): Array[T] = { 
    for(value <- values; if f(value)) yield value 
} 

或爲這樣:

def filter(values: Array[Int], f: Int => Boolean): Array[Int] = { 
    for(value <- values; if f(value)) yield value 
} 

無論如何,你可以簡單地重新寫你的方法positivesThenZerosAndNegatives這樣的:

scala> def positivesThenZerosAndNegatives(values: Array[Int]) = { 
    | values.filter(0 <) ++ values.filter(0 ==) ++ values.filter(0 >) 
    | } 
+0

我不知道我想要的過濾器已經存在。謝謝! – 2013-03-11 20:34:20