A Kleisli arrow is a function whose result is wrapped in a monad:
a -> m bMonadic code is chains of functions of the form : 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 . Kleisli arrows and their composition give exactly that. An ordinary function 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 >>= gThe reversed order is written — it reads like ordinary composition . The identity arrow is (also known as ):
pure :: a -> m aLet'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 >=> halveAndScaleWe 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, as composition and 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) -- associativityIn other words, “monad” and “Kleisli category” are two names for the same thing. The laws that look cumbersome in terms of become familiar here.