do notation
do is bind written with arrows
A do block is a chain of binds with the arrows written as <-. Each line takes a value out of the structure and names it, and the last line produces the result. The block has the type of the structure, not of the value inside it.
calc = do
x <- safeDiv 12 3
y <- safeDiv x 2
pure (x + y)
The compiler rewrites that into safeDiv 12 3 >>= \x -> safeDiv x 2 >>= \y -> pure (x + y), so the short circuit of the monad comes for free: the first Nothing skips the rest of the block. The same source works for every monad, which is why the lesson can show it over Maybe, over a list and, in the next lessons, over IO.
A do block over Maybe
Two divisions, one of which may fail, and a sum at the end. The second block divides by zero on purpose, and the whole thing is Nothing without a case:
module Main (main) where
safeDiv :: Int -> Int -> Maybe Int
safeDiv _ 0 = Nothing
safeDiv a b = Just (a `div` b)
calc :: Maybe Int
calc = do
x <- safeDiv 12 3
y <- safeDiv x 2
pure (x + y)
broken :: Maybe Int
broken = do
x <- safeDiv 12 3
y <- safeDiv x 0
pure (x + y)
main :: IO ()
main = do
print calc
print broken
ghc -Wall -O1 -o donotation donotation.hs
./donotation
Just 6
Nothing
calc is 12 divided by 3 and then by 2, so 2 + 4 = 6. broken divides 4 by 0, and the pure (x + y) line is never reached. Note that calc and broken are values, not functions: a do block over Maybe is an expression of type Maybe Int.
The same block over a list
Over a list the arrows mean "for each element", and the block becomes a nested loop. The type of the block is a list, and the last line supplies one value per combination.
module Main (main) where
import Control.Monad (unless, when)
main :: IO ()
main = do
print (do x <- ([1, 2] :: [Int]); y <- [10, 20]; pure (x + y))
when True (putStrLn "when: the condition held")
unless False (putStrLn "unless: the condition did not hold")
ghc -Wall -O1 -o listdo listdo.hs
./listdo
[11,21,12,22]
when: the condition held
unless: the condition did not hold
The four sums are the cartesian product of the two lists, in the order the loops run: for x = 1 the values 11 and 21, then for x = 2 the values 12 and 22. The block is the comprehension of the earlier lesson written with arrows, and the two are interchangeable whenever both are plain generators.
when and unless
An if with no else in a do block is written with when and unless from Control.Monad. Both take a condition and an action, and both return pure () when the condition says no, which is why they fit a block whose other lines are actions.
when (n > 0) (putStrLn "positive")
unless (n > 0) (putStrLn "not positive")
when (null xs) (putStrLn "the list is empty")
The alternative is if ... then ... else pure (), which is longer and says the same. The two functions are ordinary library definitions, not keywords, and they work for any Applicative, so they are the idiom in every monad.
What the compiler does
The rewrite is mechanical, and knowing it removes the mystery of do:
- x <- m followed by more lines becomes m >>= \x -> ....
- A line that is an action and binds nothing becomes m >> ....
- A let line becomes a let ... in around the rest of the block.
- The last line must produce the structure; a plain value there is an error, which is why pure or return appears at the end.
A pattern on the left of <- is allowed and uses the MonadFail class to handle a failed match, which in Maybe is another short circuit and in IO is an exception. The lesson on IO uses the arrows for their real purpose, and the one on monad transformers stacks two monads under one block.
Exercises
- Rewrite calc without do, using >>= and lambdas, and check that both print the same.
- Write a do block over Maybe with three lookups, one of which fails.
- Write a do block over a list that produces all pairs of two lists of strings.
- Replace when True with an if ... then ... else pure () and compare.
- Use a pattern binding (a, b) <- pure (1, 2) in a do block and print the sum.
- Explain what the compiler does to the line y <- safeDiv x 0.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is a do block a shorthand for?
Answer
A chain of binds with >>= and lambdas
do is desugared into >>=, >> and let, with the arrows naming the bound values.
-
What does
x <- mmean in a do block?Answer
Run m, take the value inside the structure and name it x
The arrow binds the value inside the monadic value for the rest of the block.
-
What happens in
brokenwhensafeDiv x 0returns Nothing?Answer
The rest of the block is skipped and the block returns Nothing
The bind of Maybe short-circuits, so pure (x + y) is never evaluated.
-
What does the list do block print for
x <- [1,2], y <- [10,20], pure (x + y)?Answer
[11,21,12,22]
The outer loop is x, so for x = 1 the sums 11 and 21 come first.
-
What does
when False (putStrLn "x")do?Answer
Nothing, it returns pure ()
when runs the action only if the condition holds and returns pure () otherwise.
-
What does this program print? ``
module Main (main) where safeDiv :: Int -> Int -> Maybe Int safeDiv _ 0 = Nothing safeDiv a b = Just (adivb) calc :: Maybe Int calc = do x <- safeDiv 12 3 y <- safeDiv x 2 pure (x + y) main :: IO () main = print calc``Answer
Just 6
The two divisions give 4 and 2, and their sum is wrapped in Just.
-
What is the type of the last line of a do block?
Answer
The same structure as the block, m a
The block builds a monadic value, so the last line must produce one, which is what pure does.
-
What does
unless True (putStrLn "x")do?Answer
Nothing, because the condition holds
unless runs the action only when the condition is False.
-
How is a
letline inside a do block desugared?Answer
As a let ... in around the rest of the block
A let in do scopes over the remaining statements, which is a let ... in the rest.
-
What does this program print?
module Main (main) where main :: IO () main = print (do x <- [1, 2]; pure (x * 10) :: [Int])Answer
[10,20]
The block maps the multiplication over both elements and collects the two results.
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