Created
December 20, 2023 10:23
-
-
Save Slakah/f17614e62bc4173ac4b11d653e2f63f8 to your computer and use it in GitHub Desktop.
Scala splitWhen for lists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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