2016-05-31 180 views
0

我想通過多少接近列表的條目來排序列表。`_`缺少參數類型

我決定嘗試使用sortWith,但下面的代碼片段:

list.sortWith(math.abs(_ - num) < math.abs(_ - num)) 

失敗,在Scala中缺少參數類型_。 列表是List[Int]類型。

繼其他線程,我知道_是某種類型曖昧,但我不知道爲什麼,(爲什麼下面的代碼片段不是類型曖昧):

scala> val sortedDudes = dudes.sortWith(_.name < _.name) 
sortedDudes: Array[Person] = Array(Al, Paul, Tyler) 

Source

+0

使您的代碼自成一體。什麼是'list'和'num'? – Jubobs

+0

列表是任何List [Int],num是任何整數。 – dcheng

+1

'math.abs(_ - num)'總是(不管它出現在什麼上下文中)'math.abs(x => x - num)'的簡稱,這是沒有意義的,不是你意。 –

回答

3
def foo = { 
    val num = 2 
    val list: List[Int] = List(1, 2) 
    list.sortWith((a, b) => math.abs(a - num) < math.abs(b - num)) 
    } 

完美地工作。這是因爲scala試圖從math.abs得到_,而不是sortWith

1

在斯卡拉,_可以用於各種不同的情況來表示不同的東西。 this question的答案應該有助於澄清其中的一些。

回到問題,似乎OP正在嘗試使用_進行參數替換。考慮下面的例子

List(1,2,5,7).filter(_ > 4) 

這裏filter需要A => Unit類型的函數,所以上述是簡寫

List(1,2,5,7).filter(x => x > 4) 

下劃線可以代表一個以上的參數,但必須被用於指到每個參數一次。這就是OP中sortedDudes片段工作的原因。因此以下是合法的。

List(1,2,5,7).reduce(_ + _) 

這是簡寫形式,

List(1,2,5,7).reduce((a,b) => a + b) 

我覺得跟原來的代碼段的問題是,編譯器無法明確地解析成(A, A) => Boolean類型的東西所要求的sortWith方法。我們可以給編譯器一些幫助,如下所示。

scala> def op(int: Int, num: Int) = math.abs(int - num) 
op: (int: Int, num: Int)Int 

scala> List(1,7,5,10).sortWith(op(_, 5) < op(_, 5)) 
res0: List[Int] = List(5, 7, 1, 10)