I want to figure out the single matching group.
As all groups are disjoint, only a single match is possible.
If no match is found other
is returned.
A single match is enough. It is not efficient to search the whole sequence How can the search be stopped after the first match?
How can this be written in a more scala-like/functional way which is less clumsy?
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
Following the advice of Find the first element that satisfies condition X in a Seq
groupings.find(_ == Seq(input))
partially works for computeGroup(1, groupings)
. It is already better as it should stop after the first match.
Some(List(1))
None
None
Unfortunately, it will not (yet) handle the other cases.