首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >说明scala中的FP排序函数

说明scala中的FP排序函数
EN

Stack Overflow用户
提问于 2017-10-05 07:01:22
回答 1查看 250关注 0票数 3

我已经开始用Scala学习FP,我的书是“Scala中的函数式编程”(Chiusano & Bjarnason,Manning出版物,2014年)

在这个练习中,您必须实现一个函数,该函数检查Array是否按照给定的比较函数(作者提供的解决方案)排序:

代码语言:javascript
复制
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)
}

当调用此函数时,例如:

代码语言:javascript
复制
isSorted(Array(1, 3, 5, 7), (x: Int, y: Int) => x > y) //evaluates to TRUE

我希望它被计算为false (不为真),因为arr没有按降序排序(7,5,3,1)。

代码语言:javascript
复制
 //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)

也许任何人都能解释这个功能,因为我不明白。一个彻底的解释是非常感激的。

非常感谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-05 07:20:43

问题在于:

代码语言:javascript
复制
else if (ordering(as(n), as(n + 1))) false

给定谓词x > y,这将为数组中的每个值生成false,从而继续传递到else子句,直到达到n >= as.length - 1为止,这将使该方法(错误地)产生真结果。

我们可以在isSorted中否定谓词

代码语言:javascript
复制
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)
}

然后:

代码语言:javascript
复制
scala> isSorted(Array(1, 3, 5, 7), (x: Int, y: Int) => x > y)
res4: Boolean = false
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46579707

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档