Skip to content
Prev Previous commit
Add scaladoc for mapAccumulateFilter
  • Loading branch information
Masynchin committed Apr 6, 2024
commit 778aad24ab51613efc39051eab67607a113d7526
12 changes: 12 additions & 0 deletions core/src/main/scala/cats/TraverseFilter.scala
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,18 @@ trait TraverseFilter[F[_]] extends FunctorFilter[F] {
override def mapFilter[A, B](fa: F[A])(f: A => Option[B]): F[B] =
traverseFilter[Id, A, B](fa)(f)

/**
* Like [[mapAccumulate]], but allows `Option` in supplied accumulating function,
* keeping only `Some`s.
*
* Example:
* {{{
* scala> import cats.syntax.all._
* scala> val sumAllAndKeepOdd = (s: Int, n: Int) => (s + n, Option.when(n % 2 == 1)(n))
* scala> List(1, 2, 3, 4).mapAccumulateFilter(0, sumAllAndKeepOdd)
* res1: (Int, List[Int]) = (10, List(1, 3))
* }}}
*/
def mapAccumulateFilter[S, A, B](init: S, fa: F[A])(f: (S, A) => (S, Option[B])): (S, F[B]) =
Comment thread
satorg marked this conversation as resolved.
traverseFilter(fa)(a => State(s => f(s, a))).run(init).value
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we override this for some of the built in collections? State is rather slow so we should avoid it for List, Vector, Chain, NonEmptyList, NonEmptyVector, ...

Copy link
Copy Markdown
Contributor Author

@Masynchin Masynchin Feb 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can copy StaticMethods.mapAccumulateFromStrictFunctor for mapAccumulateFilter, this will cover for some collections


Expand Down