Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Haskell Design Patterns

You're reading from   Haskell Design Patterns Take your Haskell and functional programming skills to the next level by exploring new idioms and design patterns

Arrow left icon
Product type Paperback
Published in Nov 2015
Publisher
ISBN-13 9781783988723
Length 166 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Ryan Lemmer Ryan Lemmer
Author Profile Icon Ryan Lemmer
Ryan Lemmer
Arrow right icon
View More author details
Toc

Imperative I/O

Even though the 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 is not meaningful anymore. We need to accumulate the chunks until we reach...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image