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 Bifunctor compose, fixes #899 #908

Merged
merged 4 commits into from
Jun 1, 2016
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
18 changes: 18 additions & 0 deletions core/src/main/scala/cats/functor/Bifunctor.scala
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,26 @@ trait Bifunctor[F[_, _]] extends Any with Serializable { self =>
* apply a function ro the "right" functor
*/
def rightMap[A,B,C](fab: F[A, B])(f: B => C): F[A,C] = bimap(fab)(identity, f)

/** The composition of two Bifunctors is itself a Bifunctor */
def compose[G[_, _]](implicit G0: Bifunctor[G]): Bifunctor[Lambda[(A, B) => F[G[A, B], G[A, B]]]] =
new CompositeBifunctor[F, G] {
val F = self
val G = G0
}
}

object Bifunctor {
def apply[F[_, _]](implicit ev: Bifunctor[F]): Bifunctor[F] = ev
}

trait CompositeBifunctor[F[_, _], G[_, _]]
extends Bifunctor[Lambda[(A, B) => F[G[A, B], G[A, B]]]] {
def F: Bifunctor[F]
def G: Bifunctor[G]

def bimap[A, B, C, D](fab: F[G[A, B], G[A, B]])(f: A => C, g: B => D): F[G[C, D], G[C, D]] = {
val innerBimap: G[A, B] => G[C, D] = gab => G.bimap(gab)(f, g)
F.bimap(fab)(innerBimap, innerBimap)
}
}
14 changes: 14 additions & 0 deletions tests/src/test/scala/cats/tests/BifunctorTests.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package cats
package tests

import cats.functor.Bifunctor
import cats.laws.discipline.{SerializableTests, BifunctorTests}

class BifunctorTest extends CatsSuite {
type Tuple2Either[A, B] = (Either[A, B], Either[A, B])
val tuple2ComposeEither: Bifunctor[Tuple2Either] =
Bifunctor[Tuple2].compose[Either]

checkAll("Tuple2 compose Either", BifunctorTests(tuple2ComposeEither).bifunctor[Int, Int, Int, String, String, String])
checkAll("Bifunctor[Tuple2 compose Either]", SerializableTests.serializable(tuple2ComposeEither))
}