Skip to content

Commit

Permalink
Add TraverseFilter instance for Queue. (#3103)
Browse files Browse the repository at this point in the history
  • Loading branch information
tanaka takaya authored and LukaJCB committed Nov 6, 2019
1 parent 5ad3c40 commit 0aaa637
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
29 changes: 29 additions & 0 deletions core/src/main/scala/cats/instances/queue.scala
Original file line number Diff line number Diff line change
Expand Up @@ -152,4 +152,33 @@ trait QueueInstances extends cats.kernel.instances.QueueInstances {
def show(fa: Queue[A]): String =
fa.iterator.map(_.show).mkString("Queue(", ", ", ")")
}

implicit def catsStdTraverseFilterForQueue: TraverseFilter[Queue] = QueueInstances.catsStdTraverseFilterForQueue
}

private object QueueInstances {
private val catsStdTraverseFilterForQueue: TraverseFilter[Queue] = new TraverseFilter[Queue] {
val traverse: Traverse[Queue] = cats.instances.queue.catsStdInstancesForQueue

override def mapFilter[A, B](fa: Queue[A])(f: (A) => Option[B]): Queue[B] =
fa.collect(Function.unlift(f))

override def filter[A](fa: Queue[A])(f: (A) => Boolean): Queue[A] = fa.filter(f)

override def collect[A, B](fa: Queue[A])(f: PartialFunction[A, B]): Queue[B] = fa.collect(f)

override def flattenOption[A](fa: Queue[Option[A]]): Queue[A] = fa.flatten

def traverseFilter[G[_], A, B](fa: Queue[A])(f: (A) => G[Option[B]])(implicit G: Applicative[G]): G[Queue[B]] =
fa.foldRight(Eval.now(G.pure(Queue.empty[B])))(
(x, xse) => G.map2Eval(f(x), xse)((i, o) => i.fold(o)(_ +: o))
)
.value

override def filterA[G[_], A](fa: Queue[A])(f: (A) => G[Boolean])(implicit G: Applicative[G]): G[Queue[A]] =
fa.foldRight(Eval.now(G.pure(Queue.empty[A])))(
(x, xse) => G.map2Eval(f(x), xse)((b, vec) => if (b) x +: vec else vec)
)
.value
}
}
5 changes: 4 additions & 1 deletion tests/src/test/scala/cats/tests/QueueSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ package cats
package tests

import scala.collection.immutable.Queue

import cats.laws.discipline.{
AlternativeTests,
CoflatMapTests,
MonadTests,
SemigroupalTests,
SerializableTests,
TraverseFilterTests,
TraverseTests
}

Expand All @@ -28,6 +28,9 @@ class QueueSuite extends CatsSuite {
checkAll("Queue[Int] with Option", TraverseTests[Queue].traverse[Int, Int, Int, Set[Int], Option, Option])
checkAll("Traverse[Queue]", SerializableTests.serializable(Traverse[Queue]))

checkAll("Queue[Int]", TraverseFilterTests[Queue].traverseFilter[Int, Int, Int])
checkAll("TraverseFilter[Queue]", SerializableTests.serializable(TraverseFilter[Queue]))

test("show") {
Queue(1, 2, 3).show should ===("Queue(1, 2, 3)")
Queue.empty[Int].show should ===("Queue()")
Expand Down

0 comments on commit 0aaa637

Please sign in to comment.