More IO Functions
Get introduced to a few more of the most common `IO` actions from the Prelude, and learn how to combine them with pure code.
We'll cover the following...
Parsing and printing
So far, we have used getLine
and putStrLn
to read and write lines as strings. But, we will need to read and work with input of other types, such as numbers. In that case, we need to convert them from strings after reading and convert them back to strings before writing.
As we have learned in the lesson on basic data types, we can use the read
and show
functions for such conversions. Here is a function that reads a number and doubles it.
ioDouble :: IO ()
ioDouble = getLine >>= \s -> putStrLn ((show . (*2) . read) s)
This is clumsy. Thankfully, there are two utility functions from the Prelude that make this easier:
readLn
combinesgetLine
and