darcs patch: add withFile and withBinaryFile (#966)

David Roundy droundy at darcs.net
Thu Oct 26 12:08:42 EDT 2006

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?)...

(But if noone has an idea how to do this in an acceptable way, then I'm all
for withFile.)
David Roundy
Dept. of Physics
Oregon State University

More information about the Libraries mailing list