Skip to content

Instantly share code, notes, and snippets.

@ryanlecompte
Created September 9, 2013 20:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanlecompte/6500902 to your computer and use it in GitHub Desktop.
Save ryanlecompte/6500902 to your computer and use it in GitHub Desktop.
groupAdjacent
@tailrec
final def groupAdjacent[A,B](
items: Seq[(A,B)],
acc: Seq[(A, Seq[B])] = Vector.empty
): Seq[(A, Seq[B])] = {
items match {
case Seq() => acc
case Seq(a, _*) =>
val (same, remaining) = items.span { case (e1, _) => a._1 == e1 }
val updated = acc :+ (a._1, same.map { _._2 })
groupAdjacent(remaining, updated)
}
}
}
// Usage:
val items = List((1,1), (1,2), (2,3), (3,4), (3,5))
scala> groupAdjacent(items)
res2: Seq[(Int, Seq[Int])] = Vector((1,List(1, 2)), (2,List(3)), (3,List(4, 5)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment