[Haskell-cafe] hGetContents and lazyness

Max Vasin max.vasin at gmail.com
Mon Sep 22 13:52:32 EDT 2008


Hello, haskellers!

Suppose we have function (it filters package filenames from apt Packages file):

> getPackageList :: FilePath -> IO [FilePath]
> getPackageList packageFile = withFile packageFile ReadMode $
>                              \h -> do c <- hGetContents h
>                                       return $ map (drop 10) $ filter (startsWith "Filename:") $ lines c -- (1)
>     where startsWith [] _ = True
>           startsWith _ [] = False
>           startsWith (x:xs) (y:ys) | x == y    = startsWith xs ys
>                                    | otherwise = False

When, I apply it to a Packages file I (surely) get an empty list. This is an expected result due to
lazyness of hGetContents. I tried changing line (1) to

> return $ map (drop 10) $ filter (startsWith "Filename:") $! lines c

or 

> return $ map (drop 10) $! filter (startsWith "Filename:") $! lines c

with no success.

Chaning it to

> return $! map (drop 10) $ filter (startsWith "Filename:") $ lines c

makes getPackageList function return several (but not all) filenames.

What I'm missing? And how can I fix my code?

--
WBR,
Max Vasin.



More information about the Haskell-Cafe mailing list