2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
10 MaybeErr(..), -- Instance of Monad
17 firstJust, firstJusts,
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 firstJust :: Maybe a -> Maybe a -> Maybe a
50 firstJust (Just a) _ = Just a
51 firstJust Nothing b = b
53 -- | Takes a list of @Maybes@ and returns the first @Just@ if there is one, or
54 -- @Nothing@ otherwise.
55 firstJusts :: [Maybe a] -> Maybe a
56 firstJusts = foldr firstJust Nothing
60 expectJust :: String -> Maybe a -> a
61 {-# INLINE expectJust #-}
62 expectJust _ (Just x) = x
63 expectJust err Nothing = error ("expectJust " ++ err)
67 mapCatMaybes :: (a -> Maybe b) -> [a] -> [b]
68 mapCatMaybes _ [] = []
69 mapCatMaybes f (x:xs) = case f x of
70 Just y -> y : mapCatMaybes f xs
71 Nothing -> mapCatMaybes f xs
76 orElse :: Maybe a -> a -> a
77 (Just x) `orElse` _ = x
78 Nothing `orElse` y = y
82 fmapM_maybe :: Monad m => (a -> m b) -> Maybe a -> m (Maybe b)
83 fmapM_maybe _ Nothing = return Nothing
84 fmapM_maybe f (Just x) = do
89 %************************************************************************
91 \subsection[MaybeT type]{The @MaybeT@ monad transformer}
93 %************************************************************************
97 newtype MaybeT m a = MaybeT {runMaybeT :: m (Maybe a)}
99 instance Functor m => Functor (MaybeT m) where
100 fmap f x = MaybeT $ fmap (fmap f) $ runMaybeT x
102 instance Monad m => Monad (MaybeT m) where
103 return = MaybeT . return . Just
104 x >>= f = MaybeT $ runMaybeT x >>= maybe (return Nothing) (runMaybeT . f)
105 fail _ = MaybeT $ return Nothing
110 %************************************************************************
112 \subsection[MaybeErr type]{The @MaybeErr@ type}
114 %************************************************************************
117 data MaybeErr err val = Succeeded val | Failed err
119 instance Monad (MaybeErr err) where
120 return v = Succeeded v
121 Succeeded v >>= k = k v
122 Failed e >>= _ = Failed e
124 isSuccess :: MaybeErr err val -> Bool
125 isSuccess (Succeeded {}) = True
126 isSuccess (Failed {}) = False
128 failME :: err -> MaybeErr err val