[project @ 2001-02-22 16:10:12 by rrt]
[ghc-hetmet.git] / ghc / lib / std / PrelMarshalError.lhs
1 % -----------------------------------------------------------------------------
2 % $Id: PrelMarshalError.lhs,v 1.1 2001/01/11 17:25:57 simonmar Exp $
3 %
4 % (c) The FFI task force, 2000
5 %
6
7 Marshalling support: Handling of common error conditions
8
9 \begin{code}
10
11 module PrelMarshalError (
12
13   -- throw an exception on specific return values
14   --
15   throwIf,       -- :: (a -> Bool) -> (a -> String) -> IO a       -> IO a
16   throwIf_,      -- :: (a -> Bool) -> (a -> String) -> IO a       -> IO ()
17   throwIfNeg,    -- :: (Ord a, Num a) 
18                  -- =>                (a -> String) -> IO a       -> IO a
19   throwIfNeg_,   -- :: (Ord a, Num a)
20                  -- =>                (a -> String) -> IO a       -> IO ()
21   throwIfNull,   -- ::                String        -> IO (Ptr a) -> IO (Ptr a)
22
23   -- discard return value
24   --
25   void           -- IO a -> IO ()
26 ) where
27
28 import PrelPtr
29 import PrelBase
30
31 -- exported functions
32 -- ------------------
33
34 -- guard an IO operation and throw an exception if the result meets the given
35 -- predicate 
36 --
37 -- * the second argument computes an error message from the result of the IO
38 --   operation
39 --
40 throwIf                 :: (a -> Bool) -> (a -> String) -> IO a -> IO a
41 throwIf pred msgfct act  = 
42   do
43     res <- act
44     (if pred res then ioError . userError . msgfct else return) res
45
46 -- like `throwIf', but discarding the result
47 --
48 throwIf_                 :: (a -> Bool) -> (a -> String) -> IO a -> IO ()
49 throwIf_ pred msgfct act  = void $ throwIf pred msgfct act
50
51 -- guards against negative result values
52 --
53 throwIfNeg :: (Ord a, Num a) => (a -> String) -> IO a -> IO a
54 throwIfNeg  = throwIf (< 0)
55
56 -- like `throwIfNeg', but discarding the result
57 --
58 throwIfNeg_ :: (Ord a, Num a) => (a -> String) -> IO a -> IO ()
59 throwIfNeg_  = throwIf_ (< 0)
60
61 -- guards against null pointers
62 --
63 throwIfNull :: String -> IO (Ptr a) -> IO (Ptr a)
64 throwIfNull  = throwIf (== nullPtr) . const
65
66 -- discard the return value of an IO action
67 --
68 void     :: IO a -> IO ()
69 void act  = act >> return ()
70
71 \end{code}