proposed addition to System.IO

Ross Paterson ross at soi.city.ac.uk
Mon Oct 23 12:45:23 EDT 2006


I propose adding the following functions to System.IO:

-- | @'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

-- | @'withBinaryFile' name mode act@ opens a file using 'openBinaryFile'
-- and passes the resulting handle to the computation @act at .  The handle
-- will be closed on exit from 'withBinaryFile', whether by normal
-- termination or by raising an exception.
withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
withBinaryFile name mode = bracket (openBinaryFile name mode) hClose

(bracket is the one from Control.Exception, if available, else the one
from System.IO.Error)

These functions are close to the Fairbairn Threshold, but just above it,
I think, and worth naming because they wrap up a pattern that should be
encouraged.



More information about the Libraries mailing list