[Haskell-cafe] Newbie question
Arthur Baars
arthurb at cs.uu.nl
Fri Aug 12 09:04:52 EDT 2005
Hi André,
The problem is that hGetContents does lazy reading of the handle.
I you do:
readDataFromFile "test.txt" >>= print
the handle is closed by hClose (in readDataFromFile) before "print"
demands the contents from the handle.
Just don't close the Handle explicitly.
This code works:
readDataFromFile filename =
do h <-openFile filename ReadMode
contents <- hGetContents h
return (lines contents)
You do not really need to close it, because hGetContents "semi-closes"
the handle. Read more:
http://www.haskell.org/onlinereport/io.html (Section 21.2.2
Semi-Closed Handles)
http://users.aber.ac.uk/afc/stricthaskell.html#semiclosed
Cheers,
Arthur
On 12-aug-05, at 14:17, André Vargas Abs da Cruz wrote:
> Hi everyone,
>
> 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.
>
> Thanks in advance
> André
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
More information about the Haskell-Cafe
mailing list