diff --git a/core/src/main/scala/cats/Functor.scala b/core/src/main/scala/cats/Functor.scala index ec5425d0be..55be0035cb 100644 --- a/core/src/main/scala/cats/Functor.scala +++ b/core/src/main/scala/cats/Functor.scala @@ -144,6 +144,20 @@ import simulacrum.typeclass */ def tupleRight[A, B](fa: F[A], b: B): F[(A, B)] = map(fa)(a => (a, b)) + /** + * Lifts `if` to Functor + * + * Example: + * {{{ + * scala> import cats.Functor + * scala> import cats.implicits.catsStdInstancesForList + * + * scala> Functor[List].ifF(List(true, false, false))(1, 0) + * res0: List[Int] = List(1, 0, 0) + * }}} + */ + def ifF[A](fb: F[Boolean])(ifTrue: => A, ifFalse: => A): F[A] = map(fb)(x => if (x) ifTrue else ifFalse) + def compose[G[_]: Functor]: Functor[λ[α => F[G[α]]]] = new ComposedFunctor[F, G] { val F = self diff --git a/tests/src/test/scala/cats/tests/FunctorSuite.scala b/tests/src/test/scala/cats/tests/FunctorSuite.scala index 8e448d6457..d92d962046 100644 --- a/tests/src/test/scala/cats/tests/FunctorSuite.scala +++ b/tests/src/test/scala/cats/tests/FunctorSuite.scala @@ -37,4 +37,21 @@ class FunctorSuite extends CatsSuite { assert(widened eq list) } } + + test("ifF equals map(if(_) ifTrue else ifFalse)") { + forAll { (l: List[Boolean], o: Option[Boolean], m: Map[String, Boolean]) => + Functor[List].ifF(l)(1, 0) should ===(l.map(if (_) 1 else 0)) + Functor[Option].ifF(o)(1, 0) should ===(o.map(if (_) 1 else 0)) + } + } + + test("ifF equals map(if(_) ifTrue else ifFalse) for concrete lists and optoins") { + Functor[List].ifF(List(true, false, false, true))(1, 0) should ===(List(1, 0, 0, 1)) + Functor[List].ifF(List.empty[Boolean])(1, 0) should ===(Nil) + Functor[Option].ifF(Some(true))(1, 0) should ===(Some(1)) + Functor[Option].ifF(Some(false))(1, 0) should ===(Some(0)) + Functor[Option].ifF(None)(1, 0) should ===(None) + + } + }