2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
10 MaybeErr(..), -- Instance of Monad
20 thenMaybe, seqMaybe, returnMaybe, failMaybe, fmapMMaybe
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
83 seqMaybe :: Maybe a -> Maybe a -> Maybe a
84 seqMaybe (Just x) _ = Just x
85 seqMaybe Nothing my = my
87 thenMaybe :: Maybe a -> (a -> Maybe b) -> Maybe b
88 thenMaybe ma mb = case ma of
92 returnMaybe :: a -> Maybe a
98 orElse :: Maybe a -> a -> a
99 (Just x) `orElse` _ = x
100 Nothing `orElse` y = y
102 fmapMMaybe :: Monad m => (a -> m b) -> Maybe a -> m (Maybe b)
103 fmapMMaybe _ Nothing = return Nothing
104 fmapMMaybe f (Just x) = f x >>= \x' -> return (Just x')
109 %************************************************************************
111 \subsection[MaybeErr type]{The @MaybeErr@ type}
113 %************************************************************************
116 data MaybeErr err val = Succeeded val | Failed err
118 instance Monad (MaybeErr err) where
119 return v = Succeeded v
120 Succeeded v >>= k = k v
121 Failed e >>= _ = Failed e
123 isSuccess :: MaybeErr err val -> Bool
124 isSuccess (Succeeded {}) = True
125 isSuccess (Failed {}) = False
127 failME :: err -> MaybeErr err val