Skip to content

Commit

Permalink
Add ifF on Functor #3040 (#3058)
Browse files Browse the repository at this point in the history
* Add `ifF` on Functor #3040

* Add `ifF` on Functor #3040 - tests added
  • Loading branch information
vasiliybondarenko authored and kailuowang committed Oct 18, 2019
1 parent e766998 commit a5c44b4
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
14 changes: 14 additions & 0 deletions core/src/main/scala/cats/Functor.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions tests/src/test/scala/cats/tests/FunctorSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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)

}

}

0 comments on commit a5c44b4

Please sign in to comment.