From d792220b3da9048441154d47a71ace0c94b15c1d Mon Sep 17 00:00:00 2001 From: Tim Spence Date: Fri, 7 Aug 2020 16:37:29 +0100 Subject: [PATCH] Order for Writer and WriterT --- core/src/main/scala/cats/data/WriterT.scala | 8 ++++++++ .../src/test/scala/cats/tests/WriterTSuite.scala | 15 +++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/core/src/main/scala/cats/data/WriterT.scala b/core/src/main/scala/cats/data/WriterT.scala index bb309a9c74a..c44f6b40625 100644 --- a/core/src/main/scala/cats/data/WriterT.scala +++ b/core/src/main/scala/cats/data/WriterT.scala @@ -320,6 +320,9 @@ final case class WriterT[F[_], L, V](run: F[(L, V)]) { G.map( F.traverse(run)(lv => G.tupleLeft(f(lv._2), lv._1)) )(WriterT.apply) + + def compare(that: WriterT[F, L, V])(implicit Ord: Order[F[(L, V)]]): Int = + Ord.compare(run, that.run) } object WriterT extends WriterTInstances with WriterTFunctions with WriterTFunctions0 { @@ -377,6 +380,11 @@ sealed abstract private[data] class WriterTInstances1 extends WriterTInstances2 implicit def catsDataFoldableForWriterTId[L](implicit F: Foldable[Id]): Foldable[WriterT[Id, L, *]] = catsDataFoldableForWriterT[Id, L](F) + + implicit def catsDataOrderForWriterT[F[_], L, V](implicit Ord: Order[F[(L, V)]]): Order[WriterT[F, L, V]] = + new Order[WriterT[F, L, V]] { + def compare(x: WriterT[F, L, V], y: WriterT[F, L, V]): Int = x.compare(y) + } } sealed abstract private[data] class WriterTInstances2 extends WriterTInstances3 { diff --git a/tests/src/test/scala/cats/tests/WriterTSuite.scala b/tests/src/test/scala/cats/tests/WriterTSuite.scala index bd1f33af97c..7c22f09b6e0 100644 --- a/tests/src/test/scala/cats/tests/WriterTSuite.scala +++ b/tests/src/test/scala/cats/tests/WriterTSuite.scala @@ -11,6 +11,7 @@ import cats.syntax.option._ import cats.syntax.eq._ import org.scalacheck.Prop._ import org.scalacheck.Test.Parameters +import cats.kernel.laws.discipline.OrderTests class WriterTSuite extends CatsSuite { type Logged[A] = Writer[ListWrapper[Int], A] @@ -386,6 +387,20 @@ class WriterTSuite extends CatsSuite { checkAll("Writer[Int, Int]", SemigroupTests[Writer[Int, Int]].semigroup) } + { + // F[(L, V)] has a semigroup + implicit val FLV: Order[ListWrapper[(Int, Int)]] = ListWrapper.order[(Int, Int)] + + Order[WriterT[ListWrapper, Int, Int]] + checkAll("WriterT[ListWrapper, Int, Int]", OrderTests[WriterT[ListWrapper, Int, Int]].order) + checkAll("Order[WriterT[ListWrapper, Int, Int]]", + SerializableTests.serializable(Order[WriterT[ListWrapper, Int, Int]]) + ) + + Order[Writer[Int, Int]] + checkAll("Writer[Int, Int]", OrderTests[Writer[Int, Int]].order) + } + { // F has an Applicative and L has a Monoid implicit val L: Monoid[ListWrapper[Int]] = ListWrapper.monoid[Int]