Skip to content

Commit ebf2b48

Browse files
committed
Add evalFold combinator to Stream
1 parent fdc16e4 commit ebf2b48

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

core/shared/src/main/scala/fs2/Stream.scala

+19
Original file line numberDiff line numberDiff line change
@@ -1081,6 +1081,25 @@ final class Stream[+F[_], +O] private[fs2] (private[fs2] val underlying: Pull[F,
10811081
go(s, this).stream
10821082
}
10831083

1084+
/** Like `[[Stream#fold]]`, but accepts a function returning an `F[_]`.
1085+
*
1086+
* @example {{{
1087+
* scala> import cats.effect.SyncIO
1088+
* scala> Stream(1,2,3,4).covary[SyncIO].evalFold(0)((acc,i) => SyncIO(acc + i)).compile.toVector.unsafeRunSync()
1089+
* res0: Vector[Int] = Vector(10)
1090+
* }}}
1091+
*/
1092+
def evalFold[F2[x] >: F[x], O2](z: O2)(f: (O2, O) => F2[O2]): Stream[F2, O2] = {
1093+
def go(z: O2, in: Stream[F2, O]): Pull[F2, O2, Unit] =
1094+
in.pull.uncons1.flatMap {
1095+
case None => Pull.output1(z)
1096+
case Some((hd, tl)) =>
1097+
Pull.eval(f(z, hd)).flatMap(ns => go(ns, tl))
1098+
}
1099+
1100+
go(z, this).stream
1101+
}
1102+
10841103
/** Effectfully maps and filters the elements of the stream depending on the optionality of the result of the
10851104
* application of the effectful function `f`.
10861105
*

core/shared/src/test/scala/fs2/StreamCombinatorsSuite.scala

+9
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,15 @@ class StreamCombinatorsSuite extends Fs2Suite {
480480
}
481481
}
482482

483+
test("evalFold") {
484+
forAllF { (s: Stream[Pure, Int], n: Int) =>
485+
val f = (_: Int) + (_: Int)
486+
s.covary[IO]
487+
.evalFold(n) { case (s, i) => IO.pure(f(s, i)) }
488+
.assertEmitsSameAs(s.fold(n)(f))
489+
}
490+
}
491+
483492
group("evalMapFilter") {
484493
test("with effectful optional identity function") {
485494
forAllF { (s: Stream[Pure, Int]) =>

0 commit comments

Comments
 (0)