有效地搜索单个第一个匹配项的序列序列

search sequence of sequences for single first match efficiently

我想搞清楚单身匹配组。 由于所有组都是不相交的,因此只能进行一次匹配。 如果未找到匹配项,则返回 other

一场比赛就够了。搜索整个序列效率不高 第一次匹配后如何停止搜索?

如何写得更scala-like/functional又不那么笨拙?

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 condition X in a Seq

的建议
groupings.find(_ == Seq(input))

部分适用于 computeGroup(1, groupings)。它已经更好了,因为它应该在第一场比赛后停止。

Some(List(1))
None
None    

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

_.contains(input) 不会做 job 吗?

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) //

找到第一个匹配组后停止