Haskell Do Notation
Do notation is a way to line up IO actions so they run in order. Each action sits on its own line inside the block.
Actions run top to bottom
The do block holds two print actions. They run in the order they are written.
main :: IO ()
main = do
putStrLn "First step"
putStrLn "Second step"Three actions in order
This block prints three numbers. The output order matches the line order.
main :: IO ()
main = do
print 10
print 20
print 30let binds a value inside do
The let line binds the plain value 5 to total. The print action then shows it.
main :: IO ()
main = do
let total = 2 + 3
print total
putStrLn "Counted"Example
main :: IO ()
main = do
let price = 6
let count = 4
print (price * count)
putStrLn "Total ready"Key points
- do: the word that starts a block of actions.
- Order: actions in a do block run from top to bottom.
- Alignment: the actions in a do block line up at the same indent.
- One action per line: each line of the block is a step that runs in turn.
- let in do: a let line binds a plain value, and it needs no in after it.
- Block result: the last action in the block gives the result of the whole block.
In this example, the two let lines bind price and count as plain values. The print action then shows their product, which is 24. The last action prints the closing line.
Note
a do block still describes one IO action, just built from smaller actions.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
In a do block, what does the line let total = 2 + 3 do?