Skip to content

Optimize Chain.traverseVoid #4695

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 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,33 @@ 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: NonEmpty[A], rhs: Chain[A], acc: G[Unit]): G[Unit] =
fa match {
case Append(l, r) =>
go(l, if (rhs.isEmpty) r else Append(r, rhs), acc)
case Wrap(as) =>
val va = Foldable[collection.immutable.Seq].traverseVoid(as)(f)
val acc1 = G.productL(acc)(va)
rhs match {
case Empty => acc1
case ne: NonEmpty[A] =>
go(ne, Empty, acc1)
}
case Singleton(a) =>
val acc1 = G.productL(acc)(f(a))
rhs match {
case Empty => acc1
case ne: NonEmpty[A] =>
go(ne, Empty, acc1)
}
}
}.value

fa match {
case Empty => G.unit
case ne: NonEmpty[A] =>
go(ne, Empty, G.unit)
}
}

final override def toIterable[A](fa: Chain[A]): Iterable[A] = new scala.collection.AbstractIterable[A] {
Expand Down
3 changes: 3 additions & 0 deletions tests/shared/src/test/scala/cats/tests/TraverseSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@
package cats.tests

import cats._
import cats.data.Chain
import cats.kernel.compat.scalaVersionSpecific._
import cats.laws.discipline.arbitrary._
import cats.syntax.all._
import org.scalacheck.Arbitrary
import org.scalacheck.Prop._
Expand Down Expand Up @@ -119,6 +121,7 @@ object TraverseSuite {

class TraverseListSuite extends TraverseSuite[List]("List")
class TraverseVectorSuite extends TraverseSuite[Vector]("Vector")
class TraverseChainSuite extends TraverseSuite[Chain]("Chain")

@annotation.nowarn("cat=deprecation")
class TraverseStreamSuite extends TraverseSuite[Stream]("Stream")
Expand Down
Loading