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 some doctest examples for Alternative methods #2070

Merged
merged 1 commit into from
Dec 6, 2017
Merged
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
34 changes: 32 additions & 2 deletions core/src/main/scala/cats/Alternative.scala
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,50 @@ import simulacrum.typeclass
* to accumulate all of the "interesting" values of the inner G, so
* if G is Option, we collect all the Some values, if G is Either,
* we collect all the Right values, etc.
*
* Example:
* {{{
* scala> import cats.implicits._
* scala> val x: List[Vector[Int]] = List(Vector(1, 2), Vector(3, 4))
* scala> Alternative[List].unite(x)
* res0: List[Int] = List(1, 2, 3, 4)
* }}}
*/
def unite[G[_], A](fga: F[G[A]])(implicit FM: Monad[F], G: Foldable[G]): F[A] =
FM.flatMap(fga) { ga =>
G.foldLeft(ga, empty[A])((acc, a) => combineK(acc, pure(a)))
}

/** Separate the inner foldable values into the "lefts" and "rights" */
/**
* Separate the inner foldable values into the "lefts" and "rights"
*
* Example:
* {{{
* scala> import cats.implicits._
* scala> val l: List[Either[String, Int]] = List(Right(1), Left("error"))
* scala> Alternative[List].separate(l)
* res0: (List[String], List[Int]) = (List(error),List(1))
* }}}
*/
def separate[G[_, _], A, B](fgab: F[G[A, B]])(implicit FM: Monad[F], G: Bifoldable[G]): (F[A], F[B]) = {
val as = FM.flatMap(fgab)(gab => G.bifoldMap(gab)(pure, _ => empty[A])(algebra[A]))
val bs = FM.flatMap(fgab)(gab => G.bifoldMap(gab)(_ => empty[B], pure)(algebra[B]))
(as, bs)
}

/** Return ().pure[F] if `condition` is true, `empty` otherwise */
/**
* Return ().pure[F] if `condition` is true, `empty` otherwise
*
* Example:
* {{{
* scala> import cats.implicits._
* scala> def even(i: Int): Option[String] = Alternative[Option].guard(i % 2 == 0).as("even")
* scala> even(2)
* res0: Option[String] = Some(even)
* scala> even(3)
* res1: Option[String] = None
* }}}
*/
def guard(condition: Boolean): F[Unit] =
if (condition) pure(()) else empty

Expand Down