我已经开始用Scala学习FP,我的书是“Scala中的函数式编程”(Chiusano & Bjarnason,Manning出版物,2014年)
在这个练习中,您必须实现一个函数,该函数检查Array是否按照给定的比较函数(作者提供的解决方案)排序:
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)
}当调用此函数时,例如:
isSorted(Array(1, 3, 5, 7), (x: Int, y: Int) => x > y) //evaluates to TRUE我希望它被计算为false (不为真),因为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)也许任何人都能解释这个功能,因为我不明白。一个彻底的解释是非常感激的。
非常感谢。
发布于 2017-10-05 07:20:43
问题在于:
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 = falsehttps://stackoverflow.com/questions/46579707
复制相似问题