Input / Output Actions
Haskell uses a special type IO to distinguish impure, input/output actions from pure expressions. The idea of the IO type is that apart from returning some value, it may also interact with the outside world along the way. The IO type has the following structure:
1
IO a
Copied!
where IO is the type name, and a is the parameterised value that it returns. For example:
1
IO Int -- an action that returns an Int
2
IO () -- an action that returns an empty tuple, called a unit
Copied!
The last example IO () represents an action that is run solely for its side-effects and simply returns an empty tuple (a void value or unit). Some basic actions in Haskell are:
1
getChar :: IO Char -- reads and returns a character from the screen
2
putChar :: Char -> IO () -- prints a character to the screen
3
return :: a -> IO a -- returns a value as an action
Copied!
Note that, strictly speaking, putChar and return are not actions, but functions that return actions. The return function is simply our one-way bridge from the pure world to the impure world that we use when we want to use pure values in actions, which we will see in examples soon. For now, let's just try out the basic actions getChar and putChar in GHCi:
1
ghci> getChar
2
1'1' -- input is 1
3
​
4
ghci> getChar
5
'\n'
6
​
7
​
8
ghci> putChar 'a'
9
a
10
​
11
ghci> putChar '\n'
12
​
Copied!
​
Copy link