Imperative I/O

Even though Haskell I/O code is purely functional, this does not prevent us from writing imperative style I/O code. Let's start by printing all the lines of the file:

import System.IO
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import Data.Char (chr)

main = do
  h <- openFile "jabberwocky.txt" ReadMode
  loop h
  hClose h
  where
    loop h' = do   
     isEof <- hIsEOF h'
     if isEof
      then putStrLn "DONE..."
      else do
        line  <- hGetLine h'
        print $ words line
        loop h'

Instead of the hGetLine function, let's use a Data.ByteString.hGet function to read from the file in chunks of 8 bytes:

  chunk  <- B.hGet h' 8
  
  print . words $ show chunk
  –- vs
  –- line  <- hGetLine h'
  –- print $ words line

The splitting of a chunk into words ...

Get Haskell Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.