Michael Saelee

March 15, 2019

The Monad typeclass further extends applicatives so that they support a new operator, >>=, called “bind”.

```
class Applicative m => Monad m where
(>>=) :: m a -> (a -> m b) -> m b
return :: a -> m a
return = pure -- "default" implementation
```

The >>= operator takes a monad, applies a function to its contents to produces a new monad, and combines (binds) the two monads to produce a final result. The binding operation effectively combines the computational contexts of the incoming monad and the one produced by the function.

Let’s consider some functions that produce Maybe monads, i.e., which return values in a context of success or failure.

Let’s use them with the bind operator:

```
_ = Just "okay" >>= censor -- => Just "okay"
_ = Just "foobar" >>= censor -- => Nothing
_ = Nothing >>= censor -- => Nothing
```

Note that the first two are equivalent to:

A common pattern is to do:

The lambda returns the result of “censor”, which returns a monad, so it can be used on the right side of the bind operator.

Keep in mind that lambdas (starting with ’') extend as far “to the right” as they can. A parenthesized version clearly revealing the lambda structure is:

We can now chain together multiple (/!) expressions:

Which can fail:

This pattern is so common and useful that Haskell provides a special syntax: “do” notation. The previous examples can be written:

Each line in a do block represents a monadic value, and “<-” appears to allow us to “extract” the contents of a monadic value. Behind the scenes, what’s really going on is that the bind operator (>>=) is automatically being invoked “between” lines!

Just as with the list applicative, the list monad supports nondeterministic programming via its bind operator.

Consider: