Skip to content

Commit

Permalink
add evalFold combinator to Stream
Browse files Browse the repository at this point in the history
  • Loading branch information
Ivan091 committed Nov 12, 2024
1 parent fdc16e4 commit a0c19cc
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
19 changes: 19 additions & 0 deletions core/shared/src/main/scala/fs2/Stream.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1081,6 +1081,25 @@ final class Stream[+F[_], +O] private[fs2] (private[fs2] val underlying: Pull[F,
go(s, this).stream
}

/** Like `[[Stream#fold]]`, but accepts a function returning an `F[_]`.
*
* @example {{{
* scala> import cats.effect.SyncIO
* scala> Stream(1,2,3,4).covary[SyncIO].evalFold(0)((acc,i) => SyncIO(acc + i)).compile.toVector.unsafeRunSync()
* res0: Vector[Int] = Vector(10)
* }}}
*/
def evalFold[F2[x] >: F[x], O2](z: O2)(f: (O2, O) => F2[O2]): Stream[F2, O2] = {
def go(z: O2, in: Stream[F2, O]): Pull[F2, O2, Unit] =
in.pull.uncons1.flatMap {
case None => Pull.output1(z)
case Some((hd, tl)) =>
Pull.eval(f(z, hd)).flatMap(ns => go(ns, tl))
}

go(z, this).stream
}

/** Effectfully maps and filters the elements of the stream depending on the optionality of the result of the
* application of the effectful function `f`.
*
Expand Down
9 changes: 9 additions & 0 deletions core/shared/src/test/scala/fs2/StreamCombinatorsSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,15 @@ class StreamCombinatorsSuite extends Fs2Suite {
}
}

test("evalFold") {
forAllF { (s: Stream[Pure, Int], n: Int) =>
val f = (_: Int) + (_: Int)
s.covary[IO]
.evalFold(n) { case (s, i) => IO.pure(f(s, i)) }
.assertEmitsSameAs(s.fold(n)(f))
}
}

group("evalMapFilter") {
test("with effectful optional identity function") {
forAllF { (s: Stream[Pure, Int]) =>
Expand Down

0 comments on commit a0c19cc

Please sign in to comment.