TExcelTAD
Home › Haskell › Haskell do-notation & IO

Haskell do-notation & IO

Pure functions can't print, read files or check the clock. Yet real programs must do all of that. Haskell's answer is the type IO a: a description of an action that, when run, interacts with the world and produces a value of type a. main is the one action the runtime executes; everything else that does I/O gets run because main (directly or indirectly) includes it.

Actions are values

An IO value is not executed when it is defined, only when it becomes part of main. You can store actions in variables and lists, and run them later, several times, or not at all:

haskell · try it yourself
sayHi :: IO ()
sayHi = putStrLn "hi!"

main :: IO ()
main = do
  let twice action = action >> action
      actions = [putStrLn "one", putStrLn "two", sayHi]
  twice sayHi
  sequence_ actions
  sequence_ (reverse actions)
  let unused = putStrLn "never printed"     -- defined, never run
  putStrLn "done"
hi!
hi!
one
two
hi!
hi!
two
one
done

sequence_ runs a list of actions in order. The unused action is a perfectly good value; it just never becomes part of main.

<- versus let

Inside a do block there are two ways to name something, and mixing them up is the most common beginner error:

Syntax Right-hand side is Name gets
x <- action an IO a action (it is run) the result, of type a
let x = expr an ordinary pure value the value itself
haskell · try it yourself
import Data.IORef

nextTicket :: IORef Int -> IO Int
nextTicket counter = do
  modifyIORef counter (+ 1)
  readIORef counter

main :: IO ()
main = do
  counter <- newIORef 100         -- run an action, bind its result
  a <- nextTicket counter
  b <- nextTicket counter
  let message = "tickets " ++ show a ++ " and " ++ show b   -- pure value
  putStrLn message
  final <- readIORef counter
  print final
tickets 101 and 102
102

IORef (from Data.IORef) is a mutable variable that can only be read and written inside IO. It is used sparingly, but it shows clearly that nextTicket counter is an action: running it twice gives two different results. Writing let a = nextTicket counter would not run anything: a would be the action itself, of type IO Int, and show a would not compile.

return doesn't return

In a do block, return x builds an action that does nothing and produces x. It does not exit the function:

haskell · try it yourself
main :: IO ()
main = do
  n <- return 5               -- same as let n = 5
  return ()                   -- does nothing; execution continues
  putStrLn ("n is " ++ show n)
  result <- pure (n * 2)      -- pure and return are the same thing
  print result
n is 5
10

Separating pure logic from I/O

Idiomatic Haskell keeps the I/O layer thin: read input, call pure functions, write output. The pure core is easy to test and reason about:

haskell · try it yourself
import Data.List (sortOn)
import Data.Ord (Down (..))
import Text.Printf (printf)

-- Pure core: no IO anywhere in these types
parseLine :: String -> (String, Int)
parseLine line = case words line of
  [name, score] -> (name, read score)
  _ -> ("?", 0)

leaderboard :: [(String, Int)] -> [String]
leaderboard scores =
  [ printf "%d. %-6s %4d" rank name score
  | (rank, (name, score)) <- zip [1 :: Int ..] (sortOn (Down . snd) scores)
  ]

-- Thin I/O shell
main :: IO ()
main = do
  let input = "mia 420\nleo 515\nzoe 380\nkai 470"   -- would be: input <- getContents
  mapM_ putStrLn (leaderboard (map parseLine (lines input)))
1. leo     515
2. kai     470
3. mia     420
4. zoe     380

printf can also return a String instead of printing, when the surrounding type asks for one.

Common IO functions

Function Type Purpose
putStr, putStrLn, print … -> IO () write to standard output
getLine IO String read one line from standard input
getContents IO String read all of standard input (lazily)
interact (String -> String) -> IO () turn a pure text function into a program
readFile, writeFile, appendFile FilePath -> … whole-file I/O
hPutStrLn stderr String -> IO () write to standard error (System.IO)
getArgs IO [String] command-line arguments (System.Environment)

Files work in the playground's temporary directory too:

haskell · try it yourself
main :: IO ()
main = do
  writeFile "/tmp/notes.txt" "buy milk\n"
  appendFile "/tmp/notes.txt" "learn monads\n"
  contents <- readFile "/tmp/notes.txt"
  putStr contents
  print (length (lines contents))
buy milk
learn monads
2

mapM_, forM_ and friends

Loops over data in IO use the monadic list functions:

haskell · try it yourself
import Control.Monad (forM_, forM, when)

main :: IO ()
main = do
  forM_ (zip [1 :: Int ..] ["plan", "build", "test"]) $ \(i, step) ->
    putStrLn (show i ++ ") " ++ step)
  lengths <- forM ["alpha", "be", "gamma"] $ \w -> do
    when (length w < 3) $ putStrLn ("short word: " ++ w)
    return (length w)
  print lengths
1) plan
2) build
3) test
short word: be
[5,2,5]

forM_ (or mapM_ with the arguments swapped) discards results; forM/mapM collect them.

Note: There is no way to "get the String out of an IO String" in pure code. You can only use the result inside another IO action, with <-. This one-way door is what keeps pure code pure, and the type checker enforces it.

Test yourself

In a do block, what is the type of line after line <- getLine?

  1. IO String
  2. String
  3. Maybe String
  4. IO ()

What does return () in the middle of a do block do?

  1. Exits the function
  2. Nothing: it is an action with no effect
  3. Throws an error
  4. Restarts the block

Which is the idiomatic structure for a Haskell program?

  1. Do everything in IO
  2. A thin IO layer around a pure core
  3. Avoid main
  4. Use IORef for every variable