I have the following Haskell program for computing a maximum sum substring of a string of integers:
{-# LANGUAGE BangPatterns #-} {-# OPTIONS_GHC -O2 #-}
import Data.Functor
import Data.Maybe
import Data.ByteString.Lazy.Char8 (getContents,lines,readInt,words)
import Prelude hiding (getContents,words,lines)
main = do
cont <- words <$> getContents
putStrLn $ show $ snd $ foldl opt (0,0) $ map (fst.fromJust.readInt) cont
opt (!c,!m) x = (max 0 (c+x),max m (c+x))
The problem with this program is that it reads the whole file into memory. The corresponding program without BytesString does not have this problem:
{-# LANGUAGE BangPatterns #-} {-# OPTIONS_GHC -O2 #-}
import Data.Functor
import Data.Maybe
main = do
cont <- words <$> getContents
putStrLn $ show $ snd $ foldl opt (0,0) $ map read cont
opt (!c,!m) x = (max 0 (c+x),max m (c+x))
It only uses a small constant amount of memory, but of course it is excruciatingly slow (about 25x slower).
The problem only occurs for programs that read very large lines. If the input is spread over multiple small lines, ByteString performs as expected.
Is there any way around this?