Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ifF on Functor #3040 #3058

Merged
merged 2 commits into from
Oct 18, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)") {
vasiliybondarenko marked this conversation as resolved.
Show resolved Hide resolved
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)

}

}