haskellcategory-theoryabstract-algebra

Do notation and Monad composition


Im a Haskell beginner and I'm still learning about Category Theory and its practical use in computer science.

I've spent last day watching couple lectures from Berkley's university about category theory, most of its content was showing a mathematical view of Rings, Semigroups, Groups, Magmas, Monoids, etc.

Hence, questions raised in my mind about monadic composition and kleisli category. Therefore, I would like to questions Haskell/Category Theory experts.

Is do notation a sort of monad composition?

Regards,

Pablo Parada


Solution

  • Do notation is just syntactic sugar for >>=. Code such as

    do x <- a
       b  -- b is an expression possibly involving x
    

    is desugared to

    a >>= \x -> b
    

    If you are studying monads in CT, you will probably find that they are being defined as functors with two natural transformations

    unit :: a -> m a        -- also known as η
    join :: m (m a) -> m a  -- also known as μ
    

    while Haskell defines

    return :: a -> m a
    (>>=)  :: m a -> (a -> m b) -> m b
    

    Both presentations are equivalent. Indeed, unit and return are exactly the same thing. Instead, join can be expressed in terms of (>>=) as follows

    join x = x >>= id
    

    and, vice versa, (>>=) can be expressed in terms of join.

    x >>= f = join (fmap f x)
    

    above note that fmap takes a -> m b and m a to return m (m b), which is then flattened to m b by join.