[Shootout-list] Haskell: new wc.hs

Roland C. Dowdeswell elric@imrryr.org
Sun, 29 Aug 2004 16:31:48 -0400


The wc.hs on the shootout is quite slow because it processes the
data many times and needs to store the contents of the file in
memory while it does.  I provide one that uses accumulating parameters
to perform both reduce runtime substantially and reduce the memory
requirements to constant memory:

import Char

main = interact $ (++"\n") . foldl1 (++) . map ((" "++) . show) . f True 0 0 0

f :: Bool -> Int -> Int -> Int -> String -> [Int]
f z l w c []                            = [l, w, c]
f z l w c (x:xs) | x == '\n'            = l `seq` f True    (l+1) w    (c+1) xs
                 | z && not (isSpace x) = w `seq` f False    l   (w+1) (c+1) xs
                 | otherwise            = c `seq` f (isSpace x) l w    (c+1) xs

p.s. not on the list, please cc: me in responses.

--
    Roland Dowdeswell                      http://www.Imrryr.ORG/~elric/