Skip to content

Commit

Permalink
Optimize Chain.traverseVoid
Browse files Browse the repository at this point in the history
  • Loading branch information
johnynek committed Jan 3, 2025
1 parent d702505 commit a9c6f31
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions core/src/main/scala/cats/data/Chain.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1258,11 +1258,22 @@ sealed abstract private[data] class ChainInstances extends ChainInstances1 {
G match {
case x: StackSafeMonad[G] => Traverse.traverseVoidDirectly(fa.iterator)(f)(x)
case _ =>
foldRight(fa, Eval.now(G.unit)) { (a, acc) =>
G.map2Eval(f(a), acc) { (_, _) =>
()
@tailrec
def go(fa: Chain[A], rhs: Chain[A], acc: G[Unit]): G[Unit] =
fa match {
case Empty =>
if (rhs.isEmpty) acc
else go(rhs, Empty, acc)
case Singleton(a) =>
go(rhs, Empty, G.productL(acc)(f(a)))
case Append(l, r) =>
go(l, if (rhs.isEmpty) r else Append(r, rhs), acc)
case Wrap(as) =>
val va = Traverse[Vector].traverseVoid(as.toVector)(f)
go(rhs, Empty, G.productL(acc)(va))
}
}.value

go(fa, Empty, G.unit)
}

final override def toIterable[A](fa: Chain[A]): Iterable[A] = new scala.collection.AbstractIterable[A] {
Expand Down

0 comments on commit a9c6f31

Please sign in to comment.