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
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With