Skip to content

Commit

Permalink
Merge pull request #4146 from atais/ifF
Browse files Browse the repository at this point in the history
added ifF to Functor
  • Loading branch information
satorg authored Mar 16, 2022
2 parents 65e7499 + fff0a3d commit 219fcfb
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
19 changes: 19 additions & 0 deletions core/src/main/scala/cats/syntax/functor.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ package syntax
trait FunctorSyntax extends Functor.ToFunctorOps {
implicit final def catsSyntaxFunctorTuple2Ops[F[_], A, B](fab: F[(A, B)]): FunctorTuple2Ops[F, A, B] =
new FunctorTuple2Ops[F, A, B](fab)

implicit final def catsSyntaxIfF[F[_]](fa: F[Boolean]): IfFOps[F] =
new IfFOps[F](fa)
}

final class FunctorTuple2Ops[F[_], A, B](private val fab: F[(A, B)]) extends AnyVal {
Expand Down Expand Up @@ -62,3 +65,19 @@ final class FunctorTuple2Ops[F[_], A, B](private val fab: F[(A, B)]) extends Any
*/
def unzip(implicit F: Functor[F]): (F[A], F[B]) = F.unzip(fab)
}

final class IfFOps[F[_]](private val fa: F[Boolean]) extends AnyVal {

/**
* Lifts `if` to Functor
*
* Example:
* {{{
* scala> import cats.syntax.all._
*
* scala> List(true, false, false).ifF(1, 0)
* res0: List[Int] = List(1, 0, 0)
* }}}
*/
def ifF[B](ifTrue: => B, ifFalse: => B)(implicit F: Functor[F]): F[B] = F.ifF(fa)(ifTrue, ifFalse)
}
3 changes: 3 additions & 0 deletions tests/src/test/scala/cats/tests/SyntaxSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,9 @@ object SyntaxSuite {

val b = mock[B]
val fb1: F[B] = fa.as(b)

val c = mock[F[Boolean]]
c.ifF(1, 0)
}

def testApply[F[_]: Apply: Semigroupal,
Expand Down

0 comments on commit 219fcfb

Please sign in to comment.