Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

.splitWhen #4543

Open
Slakah opened this issue Dec 20, 2023 · 0 comments
Open

.splitWhen #4543

Slakah opened this issue Dec 20, 2023 · 0 comments

Comments

@Slakah
Copy link
Contributor

Slakah commented Dec 20, 2023

Hiya,

I largely use cats for advent of code solutions, just to provide some common utility functions which are handy for dealing with collections.

See my last contribution for .slidingN.

The idea for this is to provide a .splitWhen which will take a Foldable[A], and split it when the supplied predicate returns true.

So something quick which I wrote for advent of code (list only, but should be workable for Foldable as well):

https://gist.github.com/Slakah/f17614e62bc4173ac4b11d653e2f63f8

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
}

Any feedback appreciated! Don't know that I have much time to work on this though!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant