Skip to content

Instantly share code, notes, and snippets.

@asflierl
Created February 23, 2016 13:18
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 asflierl/a23186848d705302fe01 to your computer and use it in GitHub Desktop.
Save asflierl/a23186848d705302fe01 to your computer and use it in GitHub Desktop.
implicit class RichTraversable[A, C[B] <: TraversableLike[B, C[B]]](val wrapped: C[A]) extends AnyVal {
def splitBy(p: A => Boolean)(implicit cb: CanBuild[Either[C[A], C[A]], C[Either[C[A], C[A]]]]): C[Either[C[A], C[A]]] = {
val builder = cb()
@tailrec def spanNext(as: C[A]): Unit =
if (as.nonEmpty) {
val ph = p(as.head)
val (append, remaining) = as.span(a => p(a) == ph)
builder += (if (ph) Right(append) else Left(append) : Either[C[A], C[A]])
spanNext(remaining)
}
spanNext(wrapped)
builder.result()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment