IO By Example

In this lesson we introduce input/output operations in Haskell.

Introduction to IO

So far, all of the code we have written has been pure functional code without side effects. Of course, this is not suitable for IO operations, as their whole point is to execute side effects and interact with the “outside world”.

So, we will need a Haskell language feature to perform impure operations. At first glance, this seems troubling. If we allow the use of impure operations in any Haskell function, we will lose the advantage of referential transparency and code that is easy to reason about.

The solution of Haskell is to introduce a special type IO a. The meaning of a value of type IO a is "an operation which performs IO and produces a value of type a". Every function that handles IO must have IO as its return type. Conversely, a function that does not ...