More IO Functions
Understand how Haskell manages input and output beyond simple strings by using functions like readLn and print. Learn to handle file reading and writing, and see how pure functions can be combined with IO actions to maintain clean code separation. This lesson guides you through reading input, processing data, and writing output safely in the IO monad.
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:
readLncombinesgetLineandreadprintcombinesshowandputStrLn
Using these, our doubling program becomes easier to read. ...