2

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.

Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76
Georg Heiler
  • 16,916
  • 36
  • 162
  • 292

1 Answers1

3

Wouldn't _.contains(input) do the 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) //

It will stop after finding the first matching group.

Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76