Kleisli arrows

A Kleisli arrow is a function whose result is wrapped in a monad:

a -> m b

Monadic code is chains of functions of the form aa mb\to m\,b: each one computes something and, along the way, produces a context. We would like to compose them as easily as pure functions with the dot (.)\mathtt{(.)}. Kleisli arrows and their composition give exactly that. An ordinary function aa b\to b is a special case of it (the context is trivial).

Two Kleisli arrows glue into one — this is Kleisli composition (its operator is nicknamed the “fish”):

(>=>) :: (a -> m b) -> (b -> m c) -> (a -> m c)
(<=<) :: (b -> m c) -> (a -> m b) -> (a -> m c)   -- the reverse “fish”

-- Kleisli composition is expressed through the monad's bind:
(f >=> g) x = f x >>= g

The reversed order is written (<=<)(\mathbin{\mathtt{<=<}}) — it reads like ordinary composition (.)\mathtt{(.)}. The identity arrow is pure\mathtt{pure} (also known as return\mathtt{return}):

pure :: a -> m a

Let's take the example from the previous section and rewrite it with arrows:

-- in the section on monads we had:
processNumber x = pure x >>= halveEven >>= halveAndScale

-- with Kleisli arrows — no argument and no pure:
processNumber = halveEven >=> halveAndScale

We will talk about categories in more detail soon; for now let's say just a couple of words, namely: take types as objects, Kleisli arrows as morphisms, (>=>)(\mathbin{\mathtt{>=>}}) as composition and pure\mathtt{pure} as the identity — and you get the Kleisli category. Its axioms are exactly the monad laws:

pure >=> f == f                       -- identity
f >=> pure == f
(f >=> g) >=> h == f >=> (g >=> h)    -- associativity

In other words, “monad” and “Kleisli category” are two names for the same thing. The laws that look cumbersome in terms of >>=\mathbin{\mathtt{>>=}} become familiar here.