Working with IO monad
In the recipes that we saw earlier, we all worked with IO, and used functions such as putStrLn :: String -> IO () or print :: Show a => a -> IO ()
. We already know that these functions print the string or a value to standard output.
In this recipe, we will open a file, read it line by line, and output it on the stdout
along with the line number. We will also understand how IO works as a monad and how IO allows a Haskell program to interact with the outside world.
How to do it...
- Create a new project
io-monad
with thesimple
Stack template:
stack new io-monad simple
- Open
src/Main.hs
; we will be editing this file.
- After initial module definition, add the following imports. Only those functions that are used in the program are imported from the corresponding module:
import System.IO (hGetLine, hIsEOF, withFile, Handle, IOMode(..)) import System.Environment (getArgs) import Control.Monad import Data.List (intercalate)
- Write...