Prime -> 2010
[haskell-report.git] / report / lib-code / IO.hs
1 module IO {- export list omitted -} where
2
3 -- Just provide an implementation of the system-independent
4 -- actions that IO exports.
5
6 try :: IO a -> IO (Either IOError a)
7 try f = catch (do r <- f
8 return (Right r))
9 (return . Left)
10
11 bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
12 bracket before after m = do
13 x <- before
14 rs <- try (m x)
15 after x
16 case rs of
17 Right r -> return r
18 Left e -> ioError e
19
20 -- variant of the above where middle computation doesn't want x
21 bracket_ :: IO a -> (a -> IO b) -> IO c -> IO c
22 bracket_ before after m = do
23 x <- before
24 rs <- try m
25 after x
26 case rs of
27 Right r -> return r
28 Left e -> ioError e