Monad and bind
A function that returns a structure
fmap takes a plain function and applies it inside a structure. The next problem is a function that itself returns a structure: a lookup that may fail, a step that may produce several results. Applying such a function with fmap gives a structure inside a structure, and >>= is the operation that flattens it.
class Applicative m => Monad m where
(>>=) :: m a -> (a -> m b) -> m b
return :: a -> m a
return is the same function as pure; the name is older and still common in documentation. The bind operator takes a value in the structure, feeds it to a function that returns the structure again, and joins the two layers. For Maybe the join means "if the value was Nothing, the result is Nothing".
Maybe is a monad
A chain of >>= over Maybe carries the failure to the end without a single case: the first Nothing short-circuits everything after it. The function that fails can be written once and used in the chain.
module Main (main) where
half :: Int -> Maybe Int
half n
| even n = Just (n `div` 2)
| otherwise = Nothing
main :: IO ()
main = do
print (Just (3 :: Int) >>= \x -> Just (x * 2))
print ((Nothing :: Maybe Int) >>= \x -> Just (x * 2))
print (Just (3 :: Int) >>= \x -> if x > 2 then Just (x + 1) else Nothing)
print (([1, 2] :: [Int]) >>= \x -> [x, x * 10])
print (half 8 >>= half)
print (half 7 >>= half)
ghc -Wall -O1 -o monad monad.hs
./monad
Just 6
Nothing
Just 4
[1,10,2,20]
Just 2
Nothing
The first three lines are the three shapes of a Maybe bind: a value passes through, a Nothing on the left stops the chain, and a Nothing produced by the function stops it too. The fifth line halves 8 to 4 and then to 2; the sixth tries 7, which is odd, and the chain answers Nothing without a case.
The list monad
The fourth line is the list monad: xs >>= f applies f to every element and concatenates the results, which is concatMap. That is why the output is [1,10,2,20]: each element is replaced by two and the four values are flattened into one list.
[1, 2] >>= \x -> [x, x * 10] -- [1,10,2,20]
[1, 2] >>= \x -> [10, 20] >>= \y -> [x + y] -- [11,21,12,22]
concatMap (\x -> [x, x * 10]) [1, 2] -- [1,10,2,20]
The second line is a chain of two binds and is the cartesian product written with bind instead of a comprehension. That equivalence is not a coincidence: a list comprehension desugars to binds, and the do notation of the next lesson is another spelling of the same chain.
The three laws
A Monad instance must satisfy three laws, and the compiler does not check them. They are the reason a chain can be refactored without changing its meaning:
- Left identity: return a >>= f == f a.
- Right identity: m >>= return == m.
- Associativity: (m >>= f) >>= g == m >>= (\x -> f x >>= g).
module Main (main) where
step :: Int -> Maybe Int
step x = Just (x + 1)
main :: IO ()
main = do
print ((pure (3 :: Int) >>= step) == step 3)
print ((Just (3 :: Int) >>= pure) == Just 3)
print
( ((Just (3 :: Int) >>= step) >>= step)
== (Just (3 :: Int) >>= \x -> step x >>= step)
)
ghc -Wall -O1 -o laws laws.hs
./laws
True
True
True
Three lines, three laws, and a program that checks them for one value and one function. hlint sees the first line and reports Monad law, left identity: it knows the law and offers to replace the expression by step 3, which is the law itself. That is a rare case where a linter hint is a lesson topic, so the hint stays.
The laws are what make do notation trustworthy: the compiler rewrites a do block into binds, and the associativity law is what allows the nesting to be rearranged. A broken instance compiles and then a refactor changes the behaviour, which is why the lesson on monad laws comes back to this.
Exercises
- Write safeSqrt :: Double -> Maybe Double that rejects negative input, and chain it twice on a Maybe value.
- Use bind to look up a key and then another key from the value, with a table of pairs.
- Check the three laws for the list monad with f x = [x, x + 1].
- Rewrite [x + y | x <- [1, 2], y <- [10, 20]] with two binds.
- Explain what Nothing >>= f returns without running it.
- Write a broken Monad instance for a two-constructor type and show which law it breaks.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
>>=do?Answer
It feeds the value inside the structure to a function that returns the structure again
Bind joins the two layers by passing the inner value to a function that produces a new structure.
-
What does
Nothing >>= \x -> Just (x + 1)return?Answer
Nothing
A Nothing on the left short-circuits the chain, and the function is never called.
-
What does
Just 3 >>= \x -> Just (x * 2)return?Answer
Just 6
The value 3 goes into the function and the result is wrapped again.
-
What does
[1, 2] >>= \x -> [x, x * 10]return?Answer
[1,10,2,20]
The list monad applies the function to each element and concatenates the results.
-
Which law is
return a >>= f == f a?Answer
Left identity
The left identity law says a return on the left contributes nothing.
-
What does this program print? ``
module Main (main) where half :: Int -> Maybe Int half n | even n = Just (ndiv2) | otherwise = Nothing main :: IO () main = print (half 7 >>= half)``Answer
Nothing
7 is odd, so the first half is Nothing and the chain stops there.
-
What is
returnin a Monad?Answer
The same operation as pure: it wraps a value
return has the type a -> m a and is the historical name of pure.
-
Which function is the list monad bind equivalent to?
Answer
concatMapBind maps and concatenates, which is exactly concatMap.
-
What does
(Just 3 >>= step) >>= stepequal, if step x = Just (x + 1)?Answer
Just 5
The value goes through two increments, 3 to 4 to 5.
-
Why do the monad laws matter?
Answer
They let do blocks be rewritten and refactored without changing the meaning
The desugaring of do and the rearrangement of a chain rely on identity and associativity.
The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev