Monad
The bind operator
A monad is a functor with a way to chain a step that itself returns a wrapped value. Without that, nesting grows one level per step:
-- the standard library defines it as:
-- class Applicative m => Monad m where
-- (>>=) :: m a -> (a -> m b) -> m b
Just 2 >>= \n -> Just (n + 1) -- Just 3
Nothing >>= \n -> Just (n + 1) -- Nothing
The shape m a -> (a -> m b) -> m b is the whole idea: take a value out of the context, feed it to a function that puts a new value back, and keep one layer instead of two.
Maybe as a monad
Three lookups in a row would need three nested cases. Bind flattens them and stops at the first failure:
prices = [("a", 3), ("b", 4)]
find :: String -> [(String, Int)] -> Maybe Int
find = lookup
total = find "a" prices >>= \pa ->
find "b" prices >>= \pb ->
pure (pa + pb)
total -- Just 7
A missing "a" short-circuits everything after it. The types stay flat: the result is Maybe Int, not Maybe (Maybe Int).
The three laws
As with functors, the compiler does not check these. Every instance in the standard library obeys them, and yours must too:
f n = Just (n + 1)
g n = Just (n * 2)
-- left identity
(pure 5 >>= f) == f 5 -- True
-- right identity
(Just 5 >>= pure) == Just 5 -- True
-- associativity
((Just 5 >>= f) >>= g)
== (Just 5 >>= \x -> f x >>= g) -- True
The laws say that chaining groups however you like, which is what lets the compiler and the reader reorder a long chain without changing its meaning.
What a monad is not
A monad is not a way to escape purity and it is not a design pattern for state. It is an interface with three methods and three laws, and Maybe, lists, functions, and IO all happen to implement it:
-- the same operator, three different behaviours
Just 1 >>= \x -> Just (x + 1) -- Just 2
[1,2] >>= \x -> [x, x * 10] -- [1,10,2,20]
getLine >>= \s -> putStrLn s -- reads, then prints
The list instance runs the rest of the chain once per element, which is exactly what a comprehension does. Lesson 32 rewrites these examples in the notation designed for them.
The code on this page was run with GHC 9.10.3 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev