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:

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

  1. Write safeSqrt :: Double -> Maybe Double that rejects negative input, and chain it twice on a Maybe value.
  2. Use bind to look up a key and then another key from the value, with a table of pairs.
  3. Check the three laws for the list monad with f x = [x, x + 1].
  4. Rewrite [x + y | x <- [1, 2], y <- [10, 20]] with two binds.
  5. Explain what Nothing >>= f returns without running it.
  6. 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.

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. Which law is return a >>= f == f a?

    Answer

    Left identity

    The left identity law says a return on the left contributes nothing.

  6. What does this program print? ``module Main (main) where half :: Int -> Maybe Int half n | even n = Just (n div 2) | 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.

  7. What is return in 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.

  8. Which function is the list monad bind equivalent to?

    Answer

    concatMap

    Bind maps and concatenates, which is exactly concatMap.

  9. What does (Just 3 >>= step) >>= step equal, if step x = Just (x + 1)?

    Answer

    Just 5

    The value goes through two increments, 3 to 4 to 5.

  10. 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

Banner image