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 guard to Alternative #1939

Merged
merged 1 commit into from
Sep 29, 2017
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
4 changes: 4 additions & 0 deletions core/src/main/scala/cats/Alternative.scala
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ import simulacrum.typeclass
(as, bs)
}

/** Return ().pure[F] if `condition` is true, `empty` otherwise */
def guard(condition: Boolean): F[Unit] =
if (condition) pure(()) else empty

override def compose[G[_]: Applicative]: Alternative[λ[α => F[G[α]]]] =
new ComposedAlternative[F, G] {
val F = self
Expand Down
21 changes: 21 additions & 0 deletions core/src/main/scala/cats/syntax/alternative.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ trait AlternativeSyntax {

implicit final def catsSyntaxAlternativeSeparate[F[_], G[_, _], A, B](fgab: F[G[A, B]]): SeparateOps[F, G, A, B] =
new SeparateOps[F, G, A, B](fgab)

implicit final def catsSyntaxAlternativeGuard(b: Boolean): GuardOps =
new GuardOps(b)
}

final class UniteOps[F[_], G[_], A](val fga: F[G[A]]) extends AnyVal {
Expand Down Expand Up @@ -47,3 +50,21 @@ final class SeparateOps[F[_], G[_, _], A, B](val fgab: F[G[A, B]]) extends AnyVa
A: Alternative[F],
G: Bifoldable[G]): (F[A], F[B]) = A.separate[G, A, B](fgab)
}

final class GuardOps(val condition: Boolean) extends AnyVal {

/**
* @see [[Alternative.guard]]
*
* Example:
* {{{
* scala> import cats.implicits._
* scala> def even(i: Int): Option[String] = (i % 2 == 0).guard[Option].as("even")
* scala> even(2)
* res0: Option[String] = Some(even)
* scala> even(3)
* res1: Option[String] = None
* }}}
*/
def guard[F[_]](implicit F: Alternative[F]): F[Unit] = F.guard(condition)
}