Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 57 ยท Functors, applicatives and monads

do-Notation Demystified

See how Haskell do blocks desugar into >>= and >>, how let and pattern matching work inside do, and why do is not just for IO.

The word do makes many beginners think Haskell has an imperative corner where ordinary rules stop. It does not. A do block is syntactic sugar: the compiler rewrites it into calls to >>= and >> from the previous lesson. Once you can do that rewrite in your head, do stops being magic.

It also works for every monad, not only IO. You can write do blocks for Maybe, lists and Either, and in each case the block means what that monad's bind means.

Real Haskell is not installed here, so the Haskell blocks are read-only. The runnable examples are JavaScript stand-ins.

From >>= to do

Here is the chain from the last lesson:

HASKELL
postcodeOf :: String -> Maybe String
postcodeOf name =
  userId name >>= \uid ->
  address uid >>= \addr ->
  postcode addr

Each >>= \x -> names a result and carries on. The do form puts the names on the left:

HASKELL
postcodeOf :: String -> Maybe String
postcodeOf name = do
  uid  <- userId name
  addr <- address uid
  postcode addr

The arrow <- means "run this step, and bind its result to the name on the left". The last line must be an expression of the monad's type (here Maybe String); its value is the value of the whole block.

Reading a do block

x <- m Run m, name its result x.
m Run m and ignore the result.
let y = e A plain local value.
Last line The block's final result.
1 / 2

The desugaring rules

Three rules cover almost everything:

HASKELL
do { e }                  =  e
do { e; stmts }           =  e >> do { stmts }
do { x <- e; stmts }      =  e >>= \x -> do { stmts }

So this block:

HASKELL
do
  a <- Just 3
  b <- Just 4
  Just (a + b)

is exactly:

HASKELL
Just 3 >>= \a ->
Just 4 >>= \b ->
Just (a + b)

And Just 3 >>= \a -> ... binds a to 3, so the result is Just 7. If you replaced any line with Nothing, the rest would be skipped and the result would be Nothing.

Layout matters

All statements in a do block must start in the same column, as explained in Your First Haskell Program. A statement continued on the next line must be indented further than the block's start.

let inside do

Use let for a plain value that does not come from a monadic step. No in keyword is needed inside a do block:

HASKELL
area :: Maybe Double -> Maybe Double -> Maybe Double
area mw mh = do
  w <- mw
  h <- mh
  let a = w * h
  return (a / 2)

let is for pure computations; <- is for monadic ones. A common slip is writing let x = Just 3 and expecting x to be unwrapped. It stays Just 3; only x <- Just 3 unwraps it.

If a name is bound with <- but never used, GHC with -Wall will warn you. Write _ <- step to say "I do not care", or just the step without an arrow.

A stand-in for Maybe

JavaScript cannot rewrite do blocks, so the stand-in below writes the desugared form with nested callbacks. This is the same shape the compiler produces. Real Haskell hides all of it behind do.

JS Desugared do for Maybe

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Pattern matching and failure

The left side of <- can be a pattern, not just a name:

HASKELL
pairs :: Maybe (Int, Int)
pairs = do
  (a, b) <- Just (1, 2)
  return (b, a)          -- Just (2,1)

What if the pattern might not match? For example Just x <- something. Then the do block calls a special method fail of the MonadFail class. The result depends on the monad:

  • Maybe returns Nothing.
  • Lists return [], dropping that element.
  • IO throws an exception.
  • Either e has no MonadFail instance, so a failable pattern is a compile error. Irrefutable patterns (such as a tuple pattern) are fine.
HASKELL
firstEvens :: [[Int]] -> [Int]
firstEvens xss = do
  (x : _) <- xss         -- empty lists are skipped
  if even x then [x] else []

-- firstEvens [[2, 3], [], [5], [8]]  ==  [2,8]

The empty list does not match (x : _), so it contributes nothing rather than crashing. That is the list monad's fail.

do for lists

A do block in the list monad reads like nested loops:

HASKELL
triples :: [(Int, Int, Int)]
triples = do
  a <- [1 .. 20]
  b <- [a .. 20]
  c <- [b .. 20]
  if a * a + b * b == c * c then return (a, b, c) else []

It is the same as the comprehension [(a, b, c) | a <- [1..20], b <- [a..20], c <- [b..20], a*a + b*b == c*c]. Comprehensions are really a specialised do for lists, a connection you can see in List Comprehensions.

JS The list monad as nested loops

Press Run (or Ctrl + Enter) to see the console output here.

No output.

do and IO

For IO, the same rules apply, and the order of lines is the order of execution because each >>= waits for the action before it:

HASKELL
main :: IO ()
main = do
  putStrLn "Name?"
  name <- getLine
  putStrLn ("Hello, " ++ name)

This desugars to putStrLn "Name?" >> (getLine >>= \name -> putStrLn ("Hello, " ++ name)). IO gets its own lesson soon; the point here is that nothing about do is specific to it.

return in Haskell is not a keyword and does not exit the block. It is an ordinary function that wraps a value: return x is pure x. A return in the middle of a do block does nothing special; later lines still run.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is do { x <- m; rest } rewritten as?

    An arrow statement becomes bind followed by a lambda that names the result and continues with the remaining statements.
  2. 2. What does the do block do { a <- Just 1; b <- Nothing; return (a + b) } give?

    As soon as a step is Nothing, the Maybe monad skips the rest and the whole block is Nothing.
  3. 3. What happens in the list monad when the pattern on the left of <- does not match?

    A failed pattern calls fail, which for lists is the empty list, so that branch produces no output.
  4. 4. Does return exit a do block early?

    return is an ordinary function equivalent to pure; it does not change control flow.

Summary

  • do is sugar: x <- m becomes m >>= \x -> ... and a plain line becomes m >> ....
  • The last statement gives the block's result and must be in the same monad.
  • Use let (without in) for pure local values and <- to unwrap monadic results.
  • A failable pattern calls fail: Nothing for Maybe, [] for lists, an exception for IO.
  • do works for every monad; return is just pure.

Next: Semigroups and Monoids.