As you should have picked up by now, Haskell is a functional and lazy language. This has some dire consequences for something apparently simple like input/output, but we can solve this with the
The Problem: Input/Output and Purity
Haskell functions are in general pure functions: when given the same arguments, they return the same results. The reason for this paradigm is that pure functions are much easier to debug and to prove correct. Test cases can also be set up much more easily, since we can be sure that nothing other than the arguments will influence a function's result. We also require pure functions not to have side effects other than returning a value: a pure function must be self-contained, and cannot open a network connection, write a file or do anything other than producing its result. This allows the Haskell compiler to optimise the code very aggressively.
However, there are very useful functions that cannot be pure: an input function, say
getLine, will return different results every time it is called; indeed, that's the point of an input function, since an input function returning always the same result would be pointless. Output operations have side effects, such as creating files or printing strings on the terminal: this is also a violation of purity, because the function is no longer self-contained.
Unwilling to drop the purity of standard functions, but unable to do without impure ones, Haskell places the latter ones in the
IO monad. In other words, what we up to now have called "IO actions" are just values in the
IO monad is built in such a way as to be "closed", that is, it is not possible to make a
String out of a
IO String. Such an extraction would be possible for other monads, such as
Maybe String or
[String], but not for
IO String. In this way, any operation involving an impure function will be "tainted" with the
IO monad, which then functions as a signal: if the
IO monad is present in a function's signature, we know that that function may have side effects or may produce different results with the same inputs.
Another advantage of using monads is that, by concatenating I/O operations with the
(>>) operators, we provide an order in which these I/O operations will be executed. This is important because Haskell is a lazy language, and can decide to evaluate functions whenever the compiler decides it is appropriate: however, this can work only for pure functions! If an operation with side effects (say, writing a log file) were to be written lazily, its entries could be in just about any order: clearly not the result we desire. Locking I/O operations inside a monad allows to define a clear operating sequence.
Combining Pure Functions and Input/Output
If all useful operations entail input/output, why do we bother with pure functions? The reason is that, thanks to monad properties, we can still have pure functions doing the heavy work, and benefit from the ease with which they can be debugged, tested, proved correct and optimised, while we use the
IO monad to get our data and deliver our results.
Let's try a simple example: suppose we have a function converting a string to upper case:
> let shout = map Data.Char.toUpper
The type of this function is clearly pure:
> :t shout shout :: [Char] -> [Char]
Suppose you apply this function to a string with many repeated characters, for example:
> shout "aaaaaaaaaaaaagh!" "AAAAAAAAAAAAAGH!"
The Haskell compiler needs to apply the function only four times: for 'a', 'g', 'h' and '!'. A C compiler or a Perl interpreter, knowing nothing about purity or self-containment, would have to call the function for all 16 characters, since they cannot be sure that the function will not change its output somehow. The
shout function is really trivial, but remember that this line of reasoning is valid for any pure function, and this optimisation capability will be extremely valuable for more complex operations: suppose, for instance, that you had a function to render a character in a particular font, which is a much more expensive operation.
shout with I/O, we ask the user to insert a string (side effect: we are writing to screen), we read it (impure: result can be different every time), we apply the (pure) function and we finally write the resulting string (again, side effect).
> putStr "Write your string: " >> getLine >>= (return . shout) >>= putStrLn Write your string: This is my string! THIS IS MY STRING!
shout to create a simple function from
IO [Char]; the rest is simple concatenation.
donotation is especially popular with the
IOmonad, since it is not possible to extract values from it, and at the same time it is very convenient to use statements with
<-to store input values that have to be used multiple times after having been acquired. The above example could be written in
do putStr "Write your string: " string <- getLine putStrLn (shout string)
- Every Haskell program starts from the
mainfunction, which has type
IO (). Therefore, in reality, every line of Haskell code you have ever run has run in conjunction with the
- A way of viewing the
IOmonad is thinking of an
IO avalue as a computation which gives a value of type
awhile changing the state of the world by doing input and output. This state of the world is hidden from you by the
IOmonad, and obviously you cannot set it. Seen this way,
IOis roughly analogous to the
Statemonad, which we will meet shortly. With
State, however, the state being changed is made of normal Haskell values, and so we can manipulate it directly with pure functions.
- Actually, there is a "back door" out of the
System.IO.Unsafe.unsafePerformIO, which will transform, say, a
IO Stringinto a
String. The naming of the function should point out clearly enough that it is usually not a good idea to use it.
- Naturally, the standard library has many useful functions for performing I/O, all of them involving the
IOmonad. Several important ones are presented in the IO chapter in Practical Haskell.