Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 57 ยท IO and the real world

IO Basics

Learn how Haskell handles input and output: the IO type, getLine, putStrLn, return versus pure, sequencing, interact and why IO actions are values.

Pure functions cannot print, read a keyboard or touch the clock, because those things would make the result depend on more than the arguments. Yet every useful program needs them. Haskell's answer is the IO type: a value of type IO a is a description of an action that, when the runtime performs it, may do something in the world and then produces an a.

That sounds abstract, but in practice IO code looks like a simple imperative script written in a do block. This lesson covers the everyday tools and the one idea that makes the rest make sense: an IO action is an ordinary value that you can store, pass around and combine. Real Haskell is read-only on this site; the runnable blocks are JavaScript stand-ins that model actions as functions.

The type of main

Every program starts at main, which has type IO (): an action that produces nothing interesting (the unit value ()).

HASKELL
main :: IO ()
main = putStrLn "Hello"

Some basic actions from the Prelude:

HASKELL
putStrLn :: String -> IO ()      -- print with a newline
putStr   :: String -> IO ()      -- print without one
print    :: Show a => a -> IO () -- putStrLn . show
getLine  :: IO String            -- read one line
getContents :: IO String         -- read all of standard input
readLn   :: Read a => IO a       -- read a line and parse it

putStrLn "Hi" is not a function that prints. It is a function that returns an action. Nothing happens until that action ends up being run by main.

Sequencing with do

Use <- to run an action and name its result, and let for ordinary pure values:

HASKELL
main :: IO ()
main = do
  putStrLn "What is your name?"
  name <- getLine
  let greeting = "Hello, " ++ name ++ "!"
  putStrLn greeting
  putStrLn ("Your name has " ++ show (length name) ++ " letters.")

Two rules trip up newcomers:

  • name <- getLine binds a String, not an IO String. The <- runs the action and gives you what it produced.
  • let has no arrow because the right side is a normal expression, not an action. Writing let line = getLine just gives a new name to the action itself and does not read anything.

The last statement of a do block decides the type of the whole block. If it is putStrLn ..., the block is an IO ().

Under the hood, do is sugar for >>= and >>, the same operators from Monads: getLine >>= \name -> putStrLn name. IO is simply one more monad.

return and pure are not "return"

In Haskell, return is an ordinary function, not a keyword that leaves a function early:

HASKELL
return :: Monad m => a -> m a
pure   :: Applicative f => a -> f a

In IO both wrap a plain value in an action that does nothing and produces that value. They are the same function in practice, and modern code prefers pure. Use it when a pure value must be handed back as an action:

HASKELL
askAge :: IO Int
askAge = do
  putStrLn "Age?"
  line <- getLine
  pure (read line)

shout :: String -> IO String
shout s = do
  putStrLn "shouting..."
  pure (map toUpper s)   -- needs: import Data.Char (toUpper)

Because pure does not stop anything, this prints both lines:

HASKELL
demo :: IO ()
demo = do
  _ <- pure 1
  putStrLn "still running"

A common mistake is writing return x in the middle and expecting an early exit. There is none; later statements still run.

Actions are values

Since an action is just a value, you can put actions in lists, return them from functions and build your own control structures:

HASKELL
import Control.Monad (forM_, when, unless, replicateM_)

main :: IO ()
main = do
  let greetings = [putStrLn "one", putStrLn "two", putStrLn "three"]
  sequence_ greetings                 -- run them in order
  forM_ [1 .. 3] $ \i ->              -- loop
    putStrLn ("line " ++ show i)
  replicateM_ 2 (putStrLn "twice")
  n <- readLn :: IO Int
  when (n > 10) $ putStrLn "big"
  unless (n > 10) $ putStrLn "small"

when and unless are plain functions that take a Bool and an action. Nothing about if or loops is built into the language for IO; the same higher-order functions you already know do the work. The one rule is that an if inside do must have both branches of the same IO type, usually written with pure () for "do nothing".

What an IO action is

A recipe Describes steps, does not run them.
A value Store it, pass it, put it in a list.
Run by main Only the runtime executes it.

Defining an action is not running it.

1 / 2
JS IO actions as values (a stand-in)

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

No output.

Reading all input: interact

Many small programs read text, transform it and print the result. interact captures that pattern. It takes a pure function String -> String, feeds it all of standard input and prints what it returns:

HASKELL
main :: IO ()
main = interact (unlines . map reverse . lines)

Everything except the single interact call is pure, which makes the logic easy to test. Input is read lazily, so a program can start printing before the input ends. Be careful with interactive prompts: because of lazy reading and output buffering, a prompt may appear late. Calling hSetBuffering stdout NoBuffering (from System.IO) fixes that.

When the data runs out, getLine throws an end-of-file error. Use isEOF from System.IO to check first:

HASKELL
import System.IO (isEOF)

loop :: Int -> IO Int
loop total = do
  done <- isEOF
  if done
    then pure total
    else do
      line <- getLine
      loop (total + read line)

Keep the pure core large

The type system lets you see which functions can touch the world. A good habit is to keep IO thin: read input, call pure functions, print results.

JS Pure core, thin IO shell

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

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the type of putStrLn "hi"?

    It is an action that prints and produces the unit value (). It is not run until it becomes part of main.
  2. 2. In name <- getLine, what is the type of name?

    <- runs the action and binds its result, so name is a plain String.
  3. 3. What does return x do in the middle of a do block in IO?

    return is an ordinary function equivalent to pure. It is not a control-flow keyword.
  4. 4. What does interact take as its argument?

    interact f reads all of stdin, applies the pure function f and prints the result.

Summary

  • IO a is a description of an action producing an a; main :: IO () is the entry point.
  • Use <- to run an action and name its result, let for pure values.
  • return and pure just wrap a value; they never exit early.
  • Actions are values, so sequence_, forM_, when and friends are ordinary functions.
  • interact and a thin IO shell around pure logic keep programs testable.

Next, we use IO for real data: Files, Arguments and Environment.