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.fromFunction, WriterT.liftFunctionK #3644

Merged
merged 3 commits into from
Nov 8, 2020
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
16 changes: 16 additions & 0 deletions core/src/main/scala/cats/data/Kleisli.scala
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,18 @@ sealed private[data] trait KleisliFunctions {
*/
def local[M[_], A, R](f: R => R)(fa: Kleisli[M, R, A]): Kleisli[M, R, A] =
Kleisli(r => fa.run(f(r)))

/**
* Lifts a function to a Kleisli.
* {{{
* scala> import cats.data.Kleisli
* scala> val stringify = Kleisli.fromFunction[Option, Int].apply(_.toString)
* scala> stringify.run(42)
* res0: Option[String] = Some(42)
* }}}
*/
def fromFunction[M[_], R]: KleisliFromFunctionPartiallyApplied[M, R] =
new KleisliFromFunctionPartiallyApplied[M, R]
}

sealed private[data] trait KleisliFunctionsBinCompat {
Expand Down Expand Up @@ -284,6 +296,10 @@ sealed private[data] trait KleisliFunctionsBinCompat {
new (Kleisli[F, A, *] ~> Kleisli[G, A, *]) { def apply[B](k: Kleisli[F, A, B]): Kleisli[G, A, B] = k.mapK(f) }
}

final class KleisliFromFunctionPartiallyApplied[M[_], R] {
def apply[A](f: R => A)(implicit M: Applicative[M]): Kleisli[M, R, A] = Kleisli(r => M.pure(f(r)))
}

sealed private[data] trait KleisliExplicitInstances {

def endoSemigroupK[F[_]](implicit FM: FlatMap[F]): SemigroupK[λ[α => Kleisli[F, α, α]]] =
Expand Down
6 changes: 6 additions & 0 deletions core/src/main/scala/cats/data/WriterT.scala
Original file line number Diff line number Diff line change
Expand Up @@ -812,4 +812,10 @@ private[data] trait WriterTFunctions {

def valueT[F[_], L, V](vf: F[V])(implicit functorF: Functor[F], monoidL: Monoid[L]): WriterT[F, L, V] =
WriterT.putT[F, L, V](vf)(monoidL.empty)

/**
* Lifts a FunctionK operating on effects to a FunctionK operating on WriterT with these effects.
*/
def liftFunctionK[F[_], G[_], A](f: F ~> G): WriterT[F, A, *] ~> WriterT[G, A, *] =
new (WriterT[F, A, *] ~> WriterT[G, A, *]) { def apply[B](k: WriterT[F, A, B]): WriterT[G, A, B] = k.mapK(f) }
}