2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
10 MaybeErr(..), -- Instance of Monad
28 %************************************************************************
30 \subsection[Maybe type]{The @Maybe@ type}
32 %************************************************************************
35 maybeToBool :: Maybe a -> Bool
36 maybeToBool Nothing = False
37 maybeToBool (Just _) = True
39 -- | Collects a list of @Justs@ into a single @Just@, returning @Nothing@ if
40 -- there are any @Nothings@.
41 allMaybes :: [Maybe a] -> Maybe [a]
42 allMaybes [] = Just []
43 allMaybes (Nothing : _) = Nothing
44 allMaybes (Just x : ms) = case allMaybes ms of
46 Just xs -> Just (x:xs)
48 -- | Takes a list of @Maybes@ and returns the first @Just@ if there is one, or
49 -- @Nothing@ otherwise.
50 firstJust :: [Maybe a] -> Maybe a
51 firstJust [] = Nothing
52 firstJust (Just x : _) = Just x
53 firstJust (Nothing : ms) = firstJust ms
57 expectJust :: String -> Maybe a -> a
58 {-# INLINE expectJust #-}
59 expectJust _ (Just x) = x
60 expectJust err Nothing = error ("expectJust " ++ err)
64 mapCatMaybes :: (a -> Maybe b) -> [a] -> [b]
65 mapCatMaybes _ [] = []
66 mapCatMaybes f (x:xs) = case f x of
67 Just y -> y : mapCatMaybes f xs
68 Nothing -> mapCatMaybes f xs
72 orElse :: Maybe a -> a -> a
73 (Just x) `orElse` _ = x
74 Nothing `orElse` y = y
77 %************************************************************************
79 \subsection[MaybeT type]{The @MaybeT@ monad transformer}
81 %************************************************************************
85 newtype MaybeT m a = MaybeT {runMaybeT :: m (Maybe a)}
87 instance Functor m => Functor (MaybeT m) where
88 fmap f x = MaybeT $ fmap (fmap f) $ runMaybeT x
90 instance Monad m => Monad (MaybeT m) where
91 return = MaybeT . return . Just
92 x >>= f = MaybeT $ runMaybeT x >>= maybe (return Nothing) (runMaybeT . f)
93 fail _ = MaybeT $ return Nothing
98 %************************************************************************
100 \subsection[MaybeErr type]{The @MaybeErr@ type}
102 %************************************************************************
105 data MaybeErr err val = Succeeded val | Failed err
107 instance Monad (MaybeErr err) where
108 return v = Succeeded v
109 Succeeded v >>= k = k v
110 Failed e >>= _ = Failed e
112 isSuccess :: MaybeErr err val -> Bool
113 isSuccess (Succeeded {}) = True
114 isSuccess (Failed {}) = False
116 failME :: err -> MaybeErr err val