2

I'm trying to find the sum of integers in a file. The code using the normal string is:

main = do
  contents <- getContents
  L.putStrLn (sumFile contents)
  where sumFile = sum . map  read. words

I tried to change it to use the Data.ByteString.Lazy module like this:

import Data.ByteString.Lazy as L

main = do
  contents <- L.getContents
  L.putStrLn (sumFile contents)
  where sumFile = sum . L.map  read. words

But this refused as words was returning a string. Then I tried using Data.ByteString.Char8 but it used a strict ByteString.

How can I make this function completely lazy?

melpomene
  • 84,125
  • 8
  • 85
  • 148
Michael Chav
  • 441
  • 5
  • 15
  • 7
    `Data.ByteString.Lazy.Char8`? – melpomene Jul 27 '15 at 22:19
  • 3
    If you are sure the encoding is latin1, then you can use that lazy `Char8` modules, as @melpomene points out. Otherwise, there's `Data.Text.Lazy` which should work with other encodings as well. – chi Jul 27 '15 at 23:22

1 Answers1

1

I found a slightly length workaround to reading the file as a ByteString and then as a list of integers. Thanks to @melpomene

import Data.ByteString.Lazy.Char8 as L
main = do
    contents <- L.getContents
    print (sumFile contents)
         where sumFile x = sum $ Prelude.map tups $ Prelude.map L.readInt (L.words x)
             where read' = tups.(L.readInt)


tups :: (Num a) => (Maybe (a, b)) -> a
tups (Just (a,b)) = a
tups Nothing = 0
Michael Chav
  • 441
  • 5
  • 15