Skip to content

Commit

Permalink
Merge pull request #4695 from typelevel/oscar/20250102_chain_traverse…
Browse files Browse the repository at this point in the history
…Void
  • Loading branch information
johnynek authored Jan 10, 2025
2 parents 765f781 + 2fb2f61 commit 304ab00
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
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

0 comments on commit 304ab00

Please sign in to comment.