(m >>= f) >>= g
= m >>= (\x -> f x >>= g)
what's different from f
and \x->f x
??
I think they're the same type a -> m b
. but it seems that the second >>=
at right side of equation treats the type of \x->f x
as m b
.
what's going wrong?
It's now easy to see that monad composition is an associative operator with left and right identities. This is a very important way to express the three monad laws, because they are precisely the laws that are required for monads to form a mathematical category.
A monad is an algebraic structure in category theory, and in Haskell it is used to describe computations as sequences of steps, and to handle side effects such as state and IO. Monads are abstract, and they have many useful concrete instances. Monads provide a way to structure a program.
A monadic function is a function with a single argument, written to its right. It is one of three possible function valences; the other two are dyadic and niladic. The term prefix function is used outside of APL to describe APL's monadic function syntax.
Bind takes a non-composable function f and returns a new function g that accepts the monadic type as input and returns the monadic type. g is composable. The unit function takes an argument of the type that f expected, and wraps it in the monadic type.
The expressions f
and \x -> f x
do, for most purposes, mean the same thing. However, the scope of a lambda expression extends as far to the right as possible, i.e. m >>= (\x -> (f x >>= g))
.
If the types are m :: m a
, f :: a -> m b
, and g :: b -> m c
, then on the left we have (m >>= f) :: m b
, and on the right we have (\x -> f x >>= g) :: a -> m c
.
So, the difference between the two expressions is just which order the (>>=)
operations are performed, much like the expressions 1 + (2 + 3)
and (1 + 2) + 3
differ only in the order in which the additions are performed.
The monad laws require that, like addition, the answer should be the same for both.
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