Skip to content
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

Alleycats: upgrade Iterable instance from Foldable to Traverse, add TraverseFilter #4152

Merged
merged 8 commits into from
Mar 27, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
21 changes: 18 additions & 3 deletions alleycats-core/src/main/scala/alleycats/std/iterable.scala
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
package alleycats
package std

import cats.{Eval, Foldable, Monoid}
import cats.data.Chain
import cats.kernel.instances.StaticMethods.wrapMutableIndexedSeq
import cats.{Applicative, Eval, Foldable, Monoid, Traverse}

object iterable extends IterableInstances

trait IterableInstances {
implicit val alleycatsStdIterableFoldable: Foldable[Iterable] =
new Foldable[Iterable] {
@deprecated("use alleycatsStdIterableTraverse", "2.7.1")
val alleycatsStdIterableFoldable: Foldable[Iterable] = alleycatsStdIterableTraverse

implicit val alleycatsStdIterableTraverse: Traverse[Iterable] =
bplommer marked this conversation as resolved.
Show resolved Hide resolved
new Traverse[Iterable] {
override def foldLeft[A, B](fa: Iterable[A], b: B)(f: (B, A) => B): B = fa.foldLeft(b)(f)

override def foldRight[A, B](fa: Iterable[A], lb: Eval[B])(f: (A, Eval[B]) => Eval[B]): Eval[B] =
Expand Down Expand Up @@ -35,5 +40,15 @@ trait IterableInstances {
override def isEmpty[A](fa: Iterable[A]): Boolean = fa.isEmpty

override def nonEmpty[A](fa: Iterable[A]): Boolean = fa.nonEmpty

// copied from List instances
override def traverse[G[_], A, B](fa: Iterable[A])(f: A => G[B])(implicit G: Applicative[G]): G[Iterable[B]] =
if (fa.isEmpty) G.pure(Iterable.empty)
else
G.map(Chain.traverseViaChain {
val as = collection.mutable.ArrayBuffer[A]()
as ++= fa
wrapMutableIndexedSeq(as)
}(f))(_.toVector)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package alleycats.tests
import alleycats.std.all._
import cats.{Eval, Foldable}
import cats.instances.all._
import cats.laws.discipline.FoldableTests
import cats.laws.discipline.TraverseTests

class IterableTests extends AlleycatsSuite {

Expand All @@ -27,5 +27,5 @@ class IterableTests extends AlleycatsSuite {
)
}

checkAll("Foldable[Iterable]", FoldableTests[Iterable].foldable[Int, Int])
checkAll("Traverse[Iterable]", TraverseTests[Iterable].traverse[Int, Int, Int, Set[Int], Option, Option])
}