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

Add WriterT Bifunctor #673

Merged
merged 2 commits into from
Nov 19, 2015
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
11 changes: 11 additions & 0 deletions core/src/main/scala/cats/data/WriterT.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package cats
package data

import cats.functor.Bifunctor

final case class WriterT[F[_], L, V](run: F[(L, V)]) {
def written(implicit functorF: Functor[F]): F[L] =
functorF.map(run)(_._1)
Expand Down Expand Up @@ -31,6 +33,9 @@ final case class WriterT[F[_], L, V](run: F[(L, V)]) {
def mapBoth[M, U](f: (L, V) => (M, U))(implicit functorF: Functor[F]): WriterT[F, M, U] =
WriterT { functorF.map(run)(f.tupled) }

def bimap[M, U](f: L => M, g: V => U)(implicit functorF: Functor[F]): WriterT[F, M, U] =
mapBoth((l, v) => (f(l), g(v)))

def mapWritten[M](f: L => M)(implicit functorF: Functor[F]): WriterT[F, M, V] =
mapBoth((l, v) => (f(l), v))

Expand All @@ -51,6 +56,12 @@ private[data] sealed abstract class WriterTInstances extends WriterTInstances0 {
// on an algebra release that includes https://github.com/non/algebra/pull/82
implicit def writerTIdEq[L, V](implicit E: Eq[(L, V)]): Eq[WriterT[Id, L, V]] =
writerTEq[Id, L, V]

implicit def writerTBifunctor[F[_]:Functor]: Bifunctor[WriterT[F, ?, ?]] =
new Bifunctor[WriterT[F, ?, ?]] {
def bimap[A, B, C, D](fab: WriterT[F, A, B])(f: A => C, g: B => D): WriterT[F, C, D] =
fab.bimap(f, g)
}
}

private[data] sealed abstract class WriterTInstances0 extends WriterTInstances1 {
Expand Down
4 changes: 4 additions & 0 deletions tests/src/test/scala/cats/tests/WriterTTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cats
package tests

import cats.data.{Writer, WriterT}
import cats.functor.Bifunctor
import cats.laws.discipline._
import cats.laws.discipline.eq._
import cats.laws.discipline.arbitrary._
Expand Down Expand Up @@ -56,6 +57,9 @@ class WriterTTests extends CatsSuite {
Functor[Writer[ListWrapper[Int], ?]]

Functor[Logged]

checkAll("WriterT[ListWrapper, ?, ?]", BifunctorTests[WriterT[ListWrapper, ?, ?]].bifunctor[Int, Int, Int, Int, Int, Int])
checkAll("Bifunctor[WriterT[ListWrapper, ?, ?]]", SerializableTests.serializable(Bifunctor[WriterT[ListWrapper, ?, ?]]))
}

// We have varying instances available depending on `F` and `L`.
Expand Down