class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
return :: a -> m a
Another function (>>) is also defined for a Monad
but for now it is worth just considering these two.
"Return" is famous, mostly because the name is so misleading. It is nothing whatsoever like return in any other language. People have suggested that "inject" might be better. What is does is simple, it takes its argument and makes it a monad of whatever type we are dealing with.
The other function (>>=) is often called "bind". Understanding it strikes at the heart of what Monads are all about, or how they can be useful (or used at the very least). Keep reading.
To understand (>>=) and (>>) consider this:
class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b -> m b
return :: a -> m a
And consider this definition.
m >> k = m >>= \_ -> kLeaving aside (>>) for now, let's look a "bind". The first argument is "m a" (something in a container). The second argument is "(a -> m b)" which is a function that takes "a", does something to it, and puts it in a container.
So bind could be thought of like this. We have something in a container. Bind removes it, applies the function to it, and rewraps it. Simple as that.
So what about (>>). It is just a handy "convenience" function.
You use it when you are binding once monadic computation to another,
and the second one does not require the result of the first one.
Here is the legal definition:
(>>) :: m a -> m b -> m b
m >> k = m >>= (\_ -> k)
Tom's Computer Info / tom@mmto.org