cats icon indicating copy to clipboard operation
cats copied to clipboard

.splitWhen

Open Slakah opened this issue 2 years ago • 0 comments

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!

Slakah avatar Dec 20 '23 10:12 Slakah