Skip to content

Commit

Permalink
Chunk - Add optimised traverse_ for StackSafeMonad.
Browse files Browse the repository at this point in the history
If our Applicative F is actually a StackSafeMonad, we can avoid
the default implementation of traverse_, based on the foldRight
method of Foldatble with Eval, and use instead a loop.
  • Loading branch information
diesalbla committed Mar 26, 2023
1 parent 897c3b8 commit 7138d2e
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions core/shared/src/main/scala/fs2/Chunk.scala
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import scala.reflect.ClassTag
import scodec.bits.{BitVector, ByteVector}
import java.nio.{Buffer => JBuffer, ByteBuffer => JByteBuffer, CharBuffer => JCharBuffer}

import cats.{Alternative, Applicative, Eq, Eval, Monad, Monoid, Traverse, TraverseFilter}
import cats._
import cats.data.{Chain, NonEmptyList}
import cats.syntax.all._

Expand Down Expand Up @@ -1232,7 +1232,17 @@ object Chunk
fa.size match {
case 0 => F.unit
case 1 => f(fa(0)).void
case _ => super.traverse_(fa)(f)
case _ =>
F match {
case sF: StackSafeMonad[F] =>
def go(ix: Int): F[Unit] =
if (ix < fa.size)
sF.flatMap(f(fa(ix)))(_ => go(ix + 1))
else sF.unit
go(0)
case _ =>
super.traverse_(fa)(f)
}
}

override def tailRecM[A, B](a: A)(f: A => Chunk[Either[A, B]]): Chunk[B] = {
Expand Down

0 comments on commit 7138d2e

Please sign in to comment.