Fwd: [Haskell-cafe] hGetContents and lazyness

Rafael Gustavo da Cunha Pereira Pinto RafaelGCPP.Linux at gmail.com
Mon Sep 22 14:46:24 EDT 2008


---------- Forwarded message ----------
From: Rafael Gustavo da Cunha Pereira Pinto <rafaelgcpp at gmail.com>
Date: Mon, Sep 22, 2008 at 15:46
Subject: Re: [Haskell-cafe] hGetContents and lazyness
To: Max Vasin <max.vasin at gmail.com>


Why don't you use OpenFile?

> getPackageList packageFile = do
>                              h <- OpenFile packageFile ReadMode
>                              c <- hGetContents h
>                              return $ map (drop 10) $ filter (startsWith
"Filename:") $ lines c

I am not at home so I don't have GHC around here, but this usually works for
me!

Anyway, it also depends on who is consuming the IO [FilePath] data returned.
It will not be evaluated unless asked for!


On Mon, Sep 22, 2008 at 14:52, Max Vasin <max.vasin at gmail.com> wrote:

> 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.
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>



-- 
Rafael Gustavo da Cunha Pereira Pinto
Electronic Engineer, MSc.



-- 
Rafael Gustavo da Cunha Pereira Pinto
Electronic Engineer, MSc.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20080922/ecbf4a0f/attachment.htm


More information about the Haskell-Cafe mailing list