scala - 有效地搜索序列序列以进行单个首次匹配
问题描述
我想找出单个匹配组。由于所有组都是不相交的,因此只有一个匹配是可能的。如果未找到匹配项,other
则返回。
一场比赛就足够了。搜索整个序列效率不高如何在第一次匹配后停止搜索?
如何以更类似于 scala/功能的方式编写它,而不那么笨拙?
val input = 1
val groupings = Seq(Seq(1), Seq(2, 4), Seq(6, 7))
def computeGroup(input: Int, groups: Seq[Seq[Int]]): String = {
val result = for (s <- groupings if (s.contains(input)))
yield s
val matchingGroup: Seq[Int] = result.flatten
if (matchingGroup.isEmpty) {
"other"
} else {
matchingGroup.mkString("-")
}
}
computeGroup(1, groupings) // expected 1
computeGroup(2, groupings) // expected 2-4
computeGroup(5, groupings) // expected other
遵循Find the first element that satisfies X in a Seq的建议
groupings.find(_ == Seq(input))
部分适用于computeGroup(1, groupings)
. 它已经更好了,因为它应该在第一场比赛后停止。
Some(List(1))
None
None
不幸的是,它(还)不会处理其他情况。
解决方案
不会_.contains(input)
做这份工作吗?
val input = 1
val groupings = Seq(Seq(1), Seq(2, 4), Seq(6, 7))
def computeGroup(input: Int, groups: Seq[Seq[Int]]): String = groups
.find(_.contains(input))
.map(_.mkString("-"))
.getOrElse("other")
computeGroup(1, groupings) // expected 1
computeGroup(2, groupings) // expected 2-4
computeGroup(5, groupings) //
找到第一个匹配组后它将停止。
推荐阅读
- python - 在 Linux 中编写脚本
- android - 由于 http 信任管理器,应用程序被 Google Play 拒绝
- strapi - 有没有办法在strapi.io的文件上传中保留原始文件名?
- java - Guava 表到带有标题的 CSVPrinter
- powershell - 尽管尝试了 TFM 中的所有内容,PowerShell Select-String 仍不匹配
- javascript - 如何在 React 中使用 `||` 进行内联测试?
- routing - 用户按 F5 时如何更快地刷新组件
- php - Wordpress - CPT、ACF - 如何自定义管理员编辑帖子页面?
- r - 文件名作为 R 中小标题列表中的变量
- windows - 以编程方式为应用设置图形性能