typestar

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

  1. initials full = concatMap (take 1) (words full) is pure, so no IO appears in its type.
  2. main = do sequences the putStrLn calls, with let name naming a value mid-block.
  3. print (length (words name)) handles a non-String value, because print is putStrLn after show.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in IO basics, step 22 of 27 in Language basics.

← Previous Next →