Skip to content

Commit

Permalink
Add ifF on Functor #3040
Browse files Browse the repository at this point in the history
  • Loading branch information
vasiliybondarenko committed Oct 8, 2019
1 parent dc44c3b commit 23345ee
Show file tree
Hide file tree
Showing 2 changed files with 22 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
8 changes: 8 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,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))
}
}

}

0 comments on commit 23345ee

Please sign in to comment.