2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
10 MaybeErr(..), -- Instance of Monad
29 %************************************************************************
31 \subsection[Maybe type]{The @Maybe@ type}
33 %************************************************************************
36 maybeToBool :: Maybe a -> Bool
37 maybeToBool Nothing = False
38 maybeToBool (Just _) = True
40 -- | Collects a list of @Justs@ into a single @Just@, returning @Nothing@ if
41 -- there are any @Nothings@.
42 allMaybes :: [Maybe a] -> Maybe [a]
43 allMaybes [] = Just []
44 allMaybes (Nothing : _) = Nothing
45 allMaybes (Just x : ms) = case allMaybes ms of
47 Just xs -> Just (x:xs)
49 -- | Takes a list of @Maybes@ and returns the first @Just@ if there is one, or
50 -- @Nothing@ otherwise.
51 firstJust :: [Maybe a] -> Maybe a
52 firstJust [] = Nothing
53 firstJust (Just x : _) = Just x
54 firstJust (Nothing : ms) = firstJust ms
58 expectJust :: String -> Maybe a -> a
59 {-# INLINE expectJust #-}
60 expectJust _ (Just x) = x
61 expectJust err Nothing = error ("expectJust " ++ err)
65 mapCatMaybes :: (a -> Maybe b) -> [a] -> [b]
66 mapCatMaybes _ [] = []
67 mapCatMaybes f (x:xs) = case f x of
68 Just y -> y : mapCatMaybes f xs
69 Nothing -> mapCatMaybes f xs
73 orElse :: Maybe a -> a -> a
74 (Just x) `orElse` _ = x
75 Nothing `orElse` y = y
79 fmapM_maybe :: Monad m => (a -> m b) -> Maybe a -> m (Maybe b)
80 fmapM_maybe _ Nothing = return Nothing
81 fmapM_maybe f (Just x) = do
86 %************************************************************************
88 \subsection[MaybeT type]{The @MaybeT@ monad transformer}
90 %************************************************************************
94 newtype MaybeT m a = MaybeT {runMaybeT :: m (Maybe a)}
96 instance Functor m => Functor (MaybeT m) where
97 fmap f x = MaybeT $ fmap (fmap f) $ runMaybeT x
99 instance Monad m => Monad (MaybeT m) where
100 return = MaybeT . return . Just
101 x >>= f = MaybeT $ runMaybeT x >>= maybe (return Nothing) (runMaybeT . f)
102 fail _ = MaybeT $ return Nothing
107 %************************************************************************
109 \subsection[MaybeErr type]{The @MaybeErr@ type}
111 %************************************************************************
114 data MaybeErr err val = Succeeded val | Failed err
116 instance Monad (MaybeErr err) where
117 return v = Succeeded v
118 Succeeded v >>= k = k v
119 Failed e >>= _ = Failed e
121 isSuccess :: MaybeErr err val -> Bool
122 isSuccess (Succeeded {}) = True
123 isSuccess (Failed {}) = False
125 failME :: err -> MaybeErr err val