Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monad's associativity rule in haskell

(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?

like image 781
snow Avatar asked Dec 01 '11 20:12

snow


People also ask

Are monads associative?

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.

How do monads work Haskell?

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.

What is a monadic function?

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.

What does the bind operator do Haskell?

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.


1 Answers

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.

like image 172
C. A. McCann Avatar answered Sep 23 '22 16:09

C. A. McCann