Haskell/Understanding monads/IO
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 IO
monad.
[edit] 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.
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 (>>=)
or (>>)
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.
[edit] 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.
To combine 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!
We combined return
with shout
to create a simple function from [Char]
to IO [Char]
; the rest is simple concatenation.
[edit] Extra observations
- The
do
notation is especially popular with theIO
monad, 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 indo
notation as:
do putStr "Write your string: " string <- getLine putStrLn (shout string)
- Every Haskell program starts from the
main
function, which has typeIO ()
. Therefore, in reality, every line of Haskell code you have ever run has run in conjunction with theIO
monad! - A way of viewing the
IO
monad is thinking of anIO a
value as a computation which gives a value of typea
while changing the state of the world by doing input and output. This state of the world is hidden from you by theIO
monad, and obviously you cannot set it. Seen this way,IO
is roughly analogous to theState
monad, which we will meet shortly. WithState
, 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
IO
monad,System.IO.Unsafe.unsafePerformIO
, which will transform, say, aIO String
into aString
. 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
IO
monad. Several important ones are presented in the IO chapter in Practical Haskell.