首页 > 解决方案 > 有效地搜索序列序列以进行单个首次匹配

问题描述

我想找出单个匹配组。由于所有组都是不相交的,因此只有一个匹配是可能的。如果未找到匹配项,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    

不幸的是,它(还)不会处理其他情况。

标签: scalafunctional-programmingsequence

解决方案


不会_.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) //

找到第一个匹配组后它将停止。


推荐阅读