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
40 @catMaybes@ takes a list of @Maybe@s and returns a list of
41 the contents of all the @Just@s in it. @allMaybes@ collects
42 a list of @Justs@ into a single @Just@, returning @Nothing@ if there
46 allMaybes :: [Maybe a] -> Maybe [a]
47 allMaybes [] = Just []
48 allMaybes (Nothing : _) = Nothing
49 allMaybes (Just x : ms) = case allMaybes ms of
51 Just xs -> Just (x:xs)
55 @firstJust@ takes a list of @Maybes@ and returns the
56 first @Just@ if there is one, or @Nothing@ otherwise.
59 firstJust :: [Maybe a] -> Maybe a
60 firstJust [] = Nothing
61 firstJust (Just x : _) = Just x
62 firstJust (Nothing : ms) = firstJust ms
66 expectJust :: String -> Maybe a -> a
67 {-# INLINE expectJust #-}
68 expectJust _ (Just x) = x
69 expectJust err Nothing = error ("expectJust " ++ err)
73 mapCatMaybes :: (a -> Maybe b) -> [a] -> [b]
74 mapCatMaybes _ [] = []
75 mapCatMaybes f (x:xs) = case f x of
76 Just y -> y : mapCatMaybes f xs
77 Nothing -> mapCatMaybes f xs
81 orElse :: Maybe a -> a -> a
82 (Just x) `orElse` _ = x
83 Nothing `orElse` y = y
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