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 Kleisli#mapK equivalent returning FunctionK #2450

Merged
merged 6 commits into from
Dec 7, 2018
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
31 changes: 30 additions & 1 deletion core/src/main/scala/cats/data/Kleisli.scala
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,11 @@ final case class Kleisli[F[_], A, B](run: A => F[B]) { self =>
def apply(a: A): F[B] = run(a)
}

object Kleisli extends KleisliInstances with KleisliFunctions with KleisliExplicitInstances {
object Kleisli
extends KleisliInstances
with KleisliFunctions
with KleisliFunctionsBinCompat
with KleisliExplicitInstances {

/**
* Internal API — shifts the execution of `run` in the `F` context.
Expand Down Expand Up @@ -143,6 +147,31 @@ sealed private[data] trait KleisliFunctions {
Kleisli(f.andThen(fa.run))
}

sealed private[data] trait KleisliFunctionsBinCompat {

/**
* Lifts a natural transformation of effects within a Kleisli
* to a transformation of Kleislis.
*
* Equivalent to running `mapK(f) on a Kleisli.
*
* {{{
* scala> import cats._, data._
* scala> val f: (List ~> Option) = λ[List ~> Option](_.headOption)
*
* scala> val k: Kleisli[List, String, Char] = Kleisli(_.toList)
* scala> k.run("foo")
* res0: List[Char] = List(f, o, o)
*
* scala> val k2: Kleisli[Option, String, Char] = Kleisli.liftFunctionK(f)(k)
* scala> k2.run("foo")
* res1: Option[Char] = Some(f)
* }}}
* */
def liftFunctionK[F[_], G[_], A](f: F ~> G): Kleisli[F, A, ?] ~> Kleisli[G, A, ?] =
λ[Kleisli[F, A, ?] ~> Kleisli[G, A, ?]](_.mapK(f))
}

sealed private[data] trait KleisliExplicitInstances {

def endoSemigroupK[F[_]](implicit FM: FlatMap[F]): SemigroupK[λ[α => Kleisli[F, α, α]]] =
Expand Down
7 changes: 7 additions & 0 deletions tests/src/test/scala/cats/tests/KleisliSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,13 @@ class KleisliSuite extends CatsSuite {
}
}

test("liftFunctionK consistent with mapK") {
val t: List ~> Option = λ[List ~> Option](_.headOption)
forAll { (f: Kleisli[List, Int, Int], i: Int) =>
(f.mapK(t).run(i)) should ===(Kleisli.liftFunctionK(t)(f).run(i))
}
}

test("flatMapF") {
forAll { (f: Kleisli[List, Int, Int], t: Int => List[Int], i: Int) =>
f.run(i).flatMap(t) should ===(f.flatMapF(t).run(i))
Expand Down