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 right and left functor to BiFunctor #1847

Merged
merged 3 commits into from
Aug 31, 2017
Merged
Show file tree
Hide file tree
Changes from 2 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
20 changes: 20 additions & 0 deletions core/src/main/scala/cats/functor/Bifunctor.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ import simulacrum.typeclass
*/
def bimap[A, B, C, D](fab: F[A, B])(f: A => C, g: B => D): F[C, D]

def rightFunctor[X]: Functor[F[X, ?]] =
new RightFunctor[F, X] {val F = self}

def leftFunctor[X]: Functor[F[?, X]] =
new LeftFunctor[F, X] {val F = self}

// derived methods
/**
* apply a function to the "left" functor
Expand Down Expand Up @@ -61,3 +67,17 @@ private[cats] trait ComposedBifunctor[F[_, _], G[_, _]]
F.bimap(fab)(innerBimap, innerBimap)
}
}

private trait LeftFunctor[F[_, _], X] extends Functor[F[?, X]] {
implicit val F: Bifunctor[F]

override def map[A, C](fax: F[A, X])(f: A => C): F[C, X] =
F.bimap(fax)(f, identity)
}

private trait RightFunctor[F[_, _], X] extends Functor[F[X, ?]] {
implicit val F: Bifunctor[F]

override def map[A, C](fxa: F[X, A])(f: A => C): F[X, C] =
F.bimap(fxa)(identity, f)
}
14 changes: 13 additions & 1 deletion tests/src/test/scala/cats/tests/BifunctorTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package cats
package tests

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

class BifunctorTest extends CatsSuite {
type Tuple2Either[A, B] = (Either[A, B], Either[A, B])
Expand All @@ -11,4 +11,16 @@ class BifunctorTest extends CatsSuite {

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

{
type LeftFunctor[A] = (Either[A, Int], Either[A, Int])
implicit val leftFunctor: Functor[LeftFunctor] = tuple2ComposeEither.leftFunctor
checkAll("Bifunctor[Tuple2 compose Either].leftFunctor", FunctorTests[LeftFunctor].functor[Int, Int, Int])
}

{
type RightFunctor[A] = (Either[Int, A], Either[Int, A])
implicit val leftFunctor: Functor[RightFunctor] = tuple2ComposeEither.rightFunctor
checkAll("Bifunctor[Tuple2 compose Either].rightFunctor", FunctorTests[RightFunctor].functor[Int, Int, Int])
}
}