This is my code for lazily reading a very large file which contains numbers separated by a new line character. Is there a way to simplify this using the ByteString module or would I have to use Data.Text

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

1 Answer 1


Here are some notes.

  1. bytestring's documentation clearly states that:

This module is intended to be imported qualified, to avoid name clashes with Prelude functions. eg.

import qualified Data.ByteString.Lazy.Char8 as C

This lets you unambiguously write map without Prelude qualifier.

  1. There are some properties of map that allow you to write map f . map g as map (f.g).

  2. tups can be rewritten as one-liner with maybe and fst

    tups = maybe 0 fst

All of this leads to following code:

import qualified Data.ByteString.Lazy.Char8 as L
main = L.getContents >>= print . sum . map (maybe 0 fst . L.readInt) . L.words

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.