Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 509
Pablo Parada Avatar asked Dec 08 '22 04:12

Pablo Parada


2 Answers

Is do notation a sort of monad composition?

There is nothing special about do notation. It is just a syntax sugar over the monad functions. A nice example from Haskell wikibook:

do x1 <- action1
   x2 <- action2
   action3 x1 x2

De-sugars to:

action1
  >>=
    \ x1 -> action2
      >>=
        \ x2 -> action3 x1 x2

Real world haskell book has a nice section explaining how this de-sugaring happens in various scenarios.

like image 55
Sibi Avatar answered Dec 15 '22 14:12

Sibi


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.

like image 39
chi Avatar answered Dec 15 '22 14:12

chi