[Haskell-cafe] Newbie question

Glynn Clements glynn at gclements.plus.com
Fri Aug 12 10:43:36 EDT 2005

André Vargas Abs da Cruz wrote:

>     I think this is a totally newbie question as i am a complete novice 
> to Haskell. I am trying to write down a few programs using GHC in order 
> to get used with the language. I am having some problems with a piece of 
> code (that is supposed to return a list of lines from a text file) which 
> I transcribe below:
> module Test where
> import IO
> readDataFromFile filename = do
>     bracket (openFile filename ReadMode) hClose
>             (\h -> do contents <- hGetContents h
>                       return (lines contents))
>     The question is: if i try to run this, it returns me nothing (just 
> an empty list). Why does this happen ? When i remove the "return" and 
> put a "print" instead, it prints everything as i expected.

hGetContents reads the file lazily; it won't actually read anything
until you try to "consume" the result. However, by that point, you
will have called hClose.

In general, you shouldn't use hClose in conjunction with lazy I/O
(hGetContents etc) unless you are certain that the data will have been

When you put the "print" in place of the return, you force the data to
be consumed immediately, so the issue doesn't arise.

Glynn Clements <glynn at gclements.plus.com>

More information about the Haskell-Cafe mailing list