Standard input and output

getLine and getContents

Standard input is an IO value like a file. getLine :: IO String reads one line without its newline, and getContents :: IO String reads everything that is left, lazily. The second is the one that makes a program usable in a pipeline, because it does not care how many lines arrive.

line <- getLine putStrLn ("you said: " ++ line) content <- getContents putStrLn ("bytes: " ++ show (length content))

getContents holds the handle open until the whole string is consumed, the same laziness as readFile. Reading it fully with length or lines closes the story; printing a prefix and exiting leaves the rest unread, which is fine, because the runtime closes the handle at the end.

interact

interact :: (String -> String) -> IO () is the whole shape of a filter: it reads all of standard input, applies a pure function and writes the result. A program that uppercases every line is three lines of Haskell and nothing else:

module Main (main) where import Data.Char (toUpper) main :: IO () main = interact (unlines . map (map toUpper) . lines)

ghc -Wall -O1 -o upper upper.hs
printf 'ab\ncd\n' | ./upper

AB
CD

The pure part is unlines . map (map toUpper) . lines: split into lines, uppercase each, join with newlines. The IO part is the single word interact. That separation is the point of the lesson on IO: the logic is a function that a test can call with a string, and the effect is at the edge.

A program in a pipeline

A counting program shows the other end: read everything, compute with pure functions, print one line. It is the shape of wc, and it works with a file, a pipe or a here-string without a change:

module Main (main) where main :: IO () main = do content <- getContents print (length (words content)) putStrLn (unwords (lines content))

ghc -Wall -O1 -o count count.hs
printf 'one two three\nfour\n' | ./count

4
one two three four

Four words become the number 4, and the two lines are joined into one. The same binary reads a file with ./count < file.txt and the output of another program with ls | ./count, which is the test of a well-behaved filter: it reads standard input and writes standard output, and nothing else.

Buffering and flushing

Output to a terminal is line buffered and output to a pipe is block buffered, so a line printed before a long computation may sit in the buffer. The hFlush function empties it, and hSetBuffering changes the policy:

hFlush stdout hSetBuffering stdout NoBuffering hSetBuffering stdout LineBuffering

A progress line printed with putStr and no newline needs hFlush stdout to appear before the next step, because without a newline a line-buffered handle has no reason to write. The same applies to a prompt: print it, flush, then read the answer, or a user of the program sees nothing until they type.

Standard error is a separate handle, stderr, and it is unbuffered by default. A message that should appear immediately goes there with hPutStrLn stderr, and the convention that keeps pipes clean is: results on standard output, diagnostics on standard error.

Exercises

  1. Write a program that reads one line with getLine and prints it reversed.
  2. Use interact to number the lines of the input.
  3. Count the characters of standard input with getContents.
  4. Run the counting program with a file as input and with a pipe, and compare the two commands.
  5. Add a prompt with putStr and hFlush stdout before a getLine.
  6. Print a warning to stderr and the result to standard output, and redirect them separately in the shell.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is the type of getLine?

    Answer

    IO String

    getLine is an action that produces a line of input as a String.

  2. What does getContents do?

    Answer

    Reads all remaining standard input as a lazy string

    It returns the rest of the input, produced on demand.

  3. What is the type of interact?

    Answer

    (String -> String) -> IO ()

    interact takes a pure function on text and runs it over standard input and output.

  4. What does interact (unlines . map (map toUpper) . lines) do with input "ab"?

    Answer

    Prints AB

    The lines are uppercased and joined again, so the output is the uppercase text.

  5. Why does a program in a pipeline need to read standard input rather than a filename?

    Answer

    The shell connects the previous program to its standard input

    A filter reads stdin and writes stdout, so it composes with the shell redirections and pipes.

  6. What does this program print? module Main (main) where main :: IO () main = print (length (words "one two\nthree"))

    Answer

    3

    The three words one, two and three are counted.

  7. What does hFlush stdout do?

    Answer

    Writes the buffered output immediately

    The buffer is emptied to the handle, which is what makes a prompt appear before input.

  8. Where should a diagnostic message go?

    Answer

    To stderr, so a pipeline keeps its data clean

    Results on stdout and diagnostics on stderr is the convention that makes pipes usable.

  9. Why might a putStr prompt not appear before getLine?

    Answer

    The output is buffered until a newline or a flush

    Without a newline a line-buffered handle waits, so hFlush is needed after the prompt.

  10. What does this program print? module Main (main) where main :: IO () main = print (map reverse (lines "ab\ncd"))

    Answer

    ["ba","dc"]

    Each single-character line reversed is itself, and unlines restores the line breaks.

The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev