Monads -Kleisli Composition

if we look at Wikipedia the definition of Kleisli it seems its something complex. Sometimes it seems like Mathematicians are actively trying to make everything complex, so developers cannot easily apply it, right ? But don’t worry it’s actually simple.

if we have a two functions g,f we know how to compose them:

But if we have two functions that return a monad we cannot directly compose them. Because in order to use the second function we need B instead of M[B] which is the result of f1.

This kind of monadic composition is called Kleisli composition.

if we have again the Identity Monad for simplicity lets see how would implement the Kleisi composition

if we have two functions :

then their composition can be done couple of ways. One way is displayed below. We could apply A to f1 : AM[B] and get M[B] the monad of B then we could apply the f2: B→M[C] to this and get a M[M[C]] and then flatMap this with the Bind operation and get The M[C] result.

An other way to do that would be this :

you can try it by yourself in this online .netFiddle:

--

--

Functional programming for the masses

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store