2017-10-05 90 views
3

我已經開始使用Scala學習FP隨書「Scala中的函數編程」(Chiusano &比亞爾納鬆,Manning出版社,2014)FP Scala的排序功能解釋

有沒有在你有一個鍛鍊實現它檢查數組是否被根據給定比較函數(如由作者提供的溶液)進行分類的功能:

def isSorted[A](as: Array[A], ordering: (A, A) => Boolean): Boolean = { 
@annotation.tailrec 
def go(n: Int): Boolean = 
    if (n >= as.length - 1) true 
    else if (ordering(as(n), as(n + 1))) false 
    else go(n + 1) 

go(0) 
} 

當調用此函數e。 G。像這樣:

isSorted(Array(1, 3, 5, 7), (x: Int, y: Int) => x > y) //evaluates to TRUE 

我希望它進行評估,以(不是真的),因爲ARR沒有被按降序排列(7,5,3,1)

//Array sorted in descending order ">" as sorting-operator 
scala> List(10, 5, 8, 1, 7).sortWith(_ > _) 
res2: List[Int] = List(10, 8, 7, 5, 1) 
分類

任何人都可以解釋的功能,因爲我只是不明白。非常感謝一個徹底的解釋。

非常感謝。

回答

2

問題是這裏:

else if (ordering(as(n), as(n + 1))) false 

鑑於謂詞x > y,這將產生false用於陣列中的每一個值,從而使延續到else子句直到n >= as.length - 1達到,這將使得該方法(錯誤地)產生真實。

我們可以否定謂詞中isSorted

def isSorted[A](as: Array[A], ordering: (A, A) => Boolean): Boolean = { 
@annotation.tailrec 
def go(n: Int): Boolean = 
    if (n >= as.length - 1) true 
    else if (!ordering(as(n), as(n + 1))) false 
    else go(n + 1) 

go(0) 
} 

然後:

scala> isSorted(Array(1, 3, 5, 7), (x: Int, y: Int) => x > y) 
res4: Boolean = false 
+1

尤瓦,非常感謝你的回答! – brandshaide