Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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
share|improve this question

1 Answer 1

up vote 2 down vote accepted

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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