Search code examples
scalascalazfunction-compositionkleisli

Using scalaz kleisli without explicit wrapping the function before


Let's say I have two functions val f: A => M[B] and val g: B => M[C] where M is monadic. Thus I want to combine them by using kleisli. What I currently do is this: kleisliU(f) andThenK g But I have not found a way to execute this combination without manually wrapping into kleisli first.

How can write something like f <???> g so that f is wrapped into kleisli automatically and then combined with g? I hope something in scalaz already exists for that and that I don't need to write my own implicit class / conversion.

Just for sake of completeness, that should also work with more functions e.g. f <???> g <???> h.


Solution

  • Once I wanted the same thing and I did not find it in scalaz, so I just wrote it myself:

    implicit def toKleisliK[M[_], A, B]: (A => M[B]) => Kleisli[M, A, B] = f => { 
        kleisli[M, A, B](a => f(a)) 
    }
    // then for example you can write such:
    val f: Int => Option[String] = ???
    val g: String => Option[Double] = ???
    val result = f andThenK g // inferred type is ReaderT[Option, Int, Double]