It should be obvious that most, if not all, programs are devoted to gathering data from outside, processing it, and providing results back to the outside world. That is, input and output are key.
Haskell’s I/O system is powerful and expressive. It is easy to work with and important to understand. Haskell strictly separates pure code from code that could cause things to occur in the world. That is, it provides a complete isolation from side effects in pure code. Besides helping programmers to reason about the correctness of their code, it also permits compilers to automatically introduce optimizations and parallelism.
We’ll begin this chapter with simple, standard-looking I/O in Haskell. Then we’ll discuss some of the more powerful options, as well as provide more detail on how I/O fits into the pure, lazy, functional Haskell world.
Let’s get started with I/O in Haskell by looking at a program that appears to be surprisingly similar to I/O in other languages such as C or Perl:
-- file: ch07/basicio.hs main = do putStrLn "Greetings! What is your name?" inpStr <- getLine putStrLn $ "Welcome to Haskell, " ++ inpStr ++ "!"
$ operator is a bit of syntactic sugar
that is equivalent to putting everything after it inside a pair of
You can compile this program to a
standalone executable, run it with runghc, or
main from within ghci. Here’s a
sample session using runghc:
runghc basicio.hsGreetings! What is your name?