From 23345eee5e2e5e1c74555b0b7b9377612a6c17a4 Mon Sep 17 00:00:00 2001 From: Bondarenko Date: Tue, 8 Oct 2019 12:43:01 +0300 Subject: [PATCH 1/2] Add `ifF` on Functor #3040 --- core/src/main/scala/cats/Functor.scala | 14 ++++++++++++++ tests/src/test/scala/cats/tests/FunctorSuite.scala | 8 ++++++++ 2 files changed, 22 insertions(+) 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..5b6281ece7 100644 --- a/tests/src/test/scala/cats/tests/FunctorSuite.scala +++ b/tests/src/test/scala/cats/tests/FunctorSuite.scala @@ -37,4 +37,12 @@ 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)) + } + } + } From ee6f3dc6742e4337e96aa4a6af16d3357cc02e26 Mon Sep 17 00:00:00 2001 From: Bondarenko Date: Tue, 8 Oct 2019 13:29:23 +0300 Subject: [PATCH 2/2] Add `ifF` on Functor #3040 - tests added --- tests/src/test/scala/cats/tests/FunctorSuite.scala | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/src/test/scala/cats/tests/FunctorSuite.scala b/tests/src/test/scala/cats/tests/FunctorSuite.scala index 5b6281ece7..d92d962046 100644 --- a/tests/src/test/scala/cats/tests/FunctorSuite.scala +++ b/tests/src/test/scala/cats/tests/FunctorSuite.scala @@ -45,4 +45,13 @@ class FunctorSuite extends CatsSuite { } } + 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) + + } + }