2
votes

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?

1
Data.ByteString.Lazy.Char8? - melpomene
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

1 Answers

1
votes

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