darcs patch: add withFile and withBinaryFile (#966)
Ross Paterson
ross at soi.city.ac.uk
Thu Oct 26 13:15:59 EDT 2006
On Thu, Oct 26, 2006 at 09:08:42AM -0700, David Roundy wrote:
> On Thu, Oct 26, 2006 at 01:15:11AM +0100, Ross Paterson wrote:
> > hunk ./System/IO.hs 369
> > +-- | @'withFile' name mode act@ opens a file using 'openFile' and passes
> > +-- the resulting handle to the computation @act at . The handle will be
> > +-- closed on exit from 'withFile', whether by normal termination or by
> > +-- raising an exception.
> > +withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
> > +withFile name mode = bracket (openFile name mode) hClose
>
> I like this function (and use ones like it all the time in darcs), but do
> wonder whether it might be possible to ensure that the Handle doesn't
> escape, which would make it ultra-cool. I can't see how to do this, except
> to put the third argument into another monad and use a phantom type, which
> would be highly awkward, to say the least. But if there were a pretty
> approach, it would be very fancy.
>
> In case I've been too vague, what I mean is that I'd like it if one could
> ensure that code such as
>
> withFile "filename" ReadMode return >>= hGetContents
>
> statically fails, rather than failing at runtime with a file handle closed
> exception. I know this is a stupid thing for the programmer to do, but
> it's nice to write library code such that the compiler can help programmers
> avoid doing stupid things. And I know there are a lot of folks who can
> figure out cleverer type hackery than I can, so one can always hope (and
> maybe ask Oleg?)...
He's already been there:
http://www.haskell.org/pipermail/haskell/2006-January/017410.html
More information about the Libraries
mailing list