[Haskell-cafe] RE: [Haskell] Re: state of HaXml?

Simon Marlow simonmar at microsoft.com
Fri Jan 5 04:34:31 EST 2007


[ moving to haskell-café... ]

Norman Ramsey wrote:
>  > There seems to be a misunderstanding here: readFile in
> itself is not the
>  > solution.  readFile is defined thus:
>  >
>  > readFile name        =  openFile name ReadMode >>= hGetContents  >
>  > and the original code was this:
>  >
>  >    load fn = do handle <- IO.openFile fn IO.ReadMode
>  >                 contents <- IO.hGetContents handle
>  >                 IO.hClose handle
>  >                 return $ XP.xmlParse fn contents  >
>  > Sure, you can replace the openFile/hGetContents pair by
> readFile, but the
>  > real problem is the presence of the hClose.  Removing that
> will solve your
>  > problem (but note that you now have no control over when
> the file is
>  > actually closed).
>
> Can I just leave it hanging and rely on the garbage collector to
> close it in the fullness of time?

Yes.  The problem I was alluding to arises when you have many lazilly-closed files, and you run into the system's open file limit because the runtime doesn't close them eagerly enough.  To be sure of closing the file at the right time, you need to force the entire file to be read (e.g. by forcing the result of the parse), then close the handle.

> Because of laziness, I believe there's no point in my writing the
> following:
>
>  >    load fn = do handle <- IO.openFile fn IO.ReadMode
>  >                 contents <- IO.hGetContents handle
>  >                 let xml = XP.xmlParse fn contents
>  >                 IO.hClose handle
>  >                 return xml
>
> Is that correct?

Yes.

Cheers,
        Simon


More information about the Haskell-Cafe mailing list