scalafunctional-programmingmonadskleisli

Function composition, Kleisli arrow, and Monadic laws


After reading this article I understand that >=> (Kleisli arrow) is just a higher order function to compose functions, that return "monadic values". For example:

val f: A => M[B] = ...
val g: B => M[C] = ...

val h: A => M[C] = f >=> g // compose f and g with Kleisli arrow

It looks like a simple composition of "simple" functions (i.e. pure functions that return simple values):

val f: A => B = ...
val g: B => C = ...

val h = f andThen g; // compose f and g

Now I guess this "simple" composition andThen conforms to certain laws

And now my questions:


Solution

  • What you have here is the immediate consequence of this construction being a category.

    1. Yes, they do conform. And that they conform is indeed the reason they are called Kleisli, because the Kleisli arrows plus types form the Kleisli category of the monad (to which every monad gives rise to). It's also why unit is called like that: it is the unit under composition of Kleisli arrows.
    2. Yes, they can be derived. Use the transformation (f <=< g) x = f =<< (g x) (where <=< is andThen, and =<< is probably something like flip(bind) in Scala). The exact steps of the derivation can be found here.