Sequencing IO with do in Haskell
A do block runs IO actions top to bottom, calling a pure helper partway through.
-- A pure helper: no IO in the type, so anything may call it.
initials :: String -> String
initials full = concatMap (take 1) (words full)
-- do threads IO actions together, running them top to bottom.
main :: IO ()
main = do
putStrLn "badge printer"
let name = "grace brewster hopper"
putStrLn (initials name)
-- print is putStrLn after show, so it takes any Show value.
print (length (words name))
putStrLn "badge ready"
How it works
initials full = concatMap (take 1) (words full)is pure, so no IO appears in its type.main = dosequences theputStrLncalls, withlet namenaming a value mid-block.print (length (words name))handles a non-String value, becauseprintisputStrLnaftershow.
Keywords and builtins used here
IOStringdoinitialsletmain
The run, in numbers
- Lines
- 13
- Characters to type
- 423
- Tokens
- 54
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 43 seconds.
Step 1 of 3 in IO basics, step 22 of 27 in Language basics.