Skip to content

Commit

Permalink
Add bisequence and bimap examples
Browse files Browse the repository at this point in the history
This was originally part of typelevel#1194, but since it's looking uncertain
whether or not that will go forward, I'm separating it to here.
  • Loading branch information
ceedubs committed Jul 28, 2016
1 parent 5b35e84 commit d72e69b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
27 changes: 26 additions & 1 deletion core/src/main/scala/cats/Bitraverse.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,35 @@ import cats.functor.{Bifunctor, ComposedBifunctor}
* A type class abstracting over types that give rise to two independent [[cats.Traverse]]s.
*/
trait Bitraverse[F[_, _]] extends Bifoldable[F] with Bifunctor[F] { self =>

/** Traverse each side of the structure with the given functions */
def bitraverse[G[_]: Applicative, A, B, C, D](fab: F[A, B])(f: A => G[C], g: B => G[D]): G[F[C, D]]

/** Sequence each side of the structure with the given functions */
/**
* Sequence each side of the structure with the given functions.
*
* Example:
* {{{
* scala> import cats.data.Xor
* scala> import cats.implicits._
*
* scala> val rightSome: Option[String] Xor Option[Int] = Xor.right(Some(3))
* scala> rightSome.bisequence
* res0: Option[String Xor Int] = Some(Right(3))
*
* scala> val rightNone: Option[String] Xor Option[Int] = Xor.right(None)
* scala> rightNone.bisequence
* res0: Option[String Xor Int] = None
*
* scala> val leftSome: Option[String] Xor Option[Int] = Xor.left(Some("foo"))
* scala> leftSome.bisequence
* res0: Option[String Xor Int] = Some(Left(foo))
*
* scala> val leftNone: Option[String] Xor Option[Int] = Xor.left(None)
* scala> leftNone.bisequence
* res0: Option[String Xor Int] = None
* }}}
*/
def bisequence[G[_]: Applicative, A, B](fab: F[G[A], G[B]]): G[F[A, B]] =
bitraverse(fab)(identity, identity)

Expand Down
9 changes: 9 additions & 0 deletions core/src/main/scala/cats/functor/Bifunctor.scala
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,15 @@ trait Bifunctor[F[_, _]] extends Any with Serializable { self =>
/**
* The quintessential method of the Bifunctor trait, it applies a
* function to each "side" of the bifunctor.
*
* Example:
* {{{
* scala> import cats.implicits._
*
* scala> val x: (List[String], Int) = (List("foo", "bar"), 3)
* scala> x.bimap(_.headOption, _.toLong + 1)
* res0: (Option[String], Long) = (Some(foo),4)
* }}}
*/
def bimap[A, B, C, D](fab: F[A, B])(f: A => C, g: B => D): F[C, D]

Expand Down

0 comments on commit d72e69b

Please sign in to comment.