Skip to content

Instantly share code, notes, and snippets.

@Slakah
Created December 20, 2023 10:23
Show Gist options
  • Save Slakah/f17614e62bc4173ac4b11d653e2f63f8 to your computer and use it in GitHub Desktop.
Save Slakah/f17614e62bc4173ac4b11d653e2f63f8 to your computer and use it in GitHub Desktop.
Scala splitWhen for lists
def splitWhen[A](list: List[A], f: A => Boolean): List[List[A]] = {
list.reverse.foldLeft((List.empty[List[A]], true)) {
case ((Nil, _), e) if f(e) => (Nil, true)
case ((Nil, _), e) => (List(List(e)), false)
case ((head :: tail, _), e) if f(e) => (head :: tail, true)
case ((head :: tail, false), e) => ((e :: head) :: tail, false)
case ((head :: tail, true), e) => (List(e) :: head :: tail, false)
}._1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment