2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
10 MaybeErr(..), -- Instance of Monad
27 %************************************************************************
29 \subsection[Maybe type]{The @Maybe@ type}
31 %************************************************************************
34 maybeToBool :: Maybe a -> Bool
35 maybeToBool Nothing = False
36 maybeToBool (Just _) = True
39 @catMaybes@ takes a list of @Maybe@s and returns a list of
40 the contents of all the @Just@s in it. @allMaybes@ collects
41 a list of @Justs@ into a single @Just@, returning @Nothing@ if there
45 allMaybes :: [Maybe a] -> Maybe [a]
46 allMaybes [] = Just []
47 allMaybes (Nothing : _) = Nothing
48 allMaybes (Just x : ms) = case allMaybes ms of
50 Just xs -> Just (x:xs)
54 @firstJust@ takes a list of @Maybes@ and returns the
55 first @Just@ if there is one, or @Nothing@ otherwise.
58 firstJust :: [Maybe a] -> Maybe a
59 firstJust [] = Nothing
60 firstJust (Just x : _) = Just x
61 firstJust (Nothing : ms) = firstJust ms
65 expectJust :: String -> Maybe a -> a
66 {-# INLINE expectJust #-}
67 expectJust _ (Just x) = x
68 expectJust err Nothing = error ("expectJust " ++ err)
72 mapCatMaybes :: (a -> Maybe b) -> [a] -> [b]
73 mapCatMaybes _ [] = []
74 mapCatMaybes f (x:xs) = case f x of
75 Just y -> y : mapCatMaybes f xs
76 Nothing -> mapCatMaybes f xs
80 orElse :: Maybe a -> a -> a
81 (Just x) `orElse` _ = x
82 Nothing `orElse` y = y
86 %************************************************************************
88 \subsection[MaybeErr type]{The @MaybeErr@ type}
90 %************************************************************************
93 data MaybeErr err val = Succeeded val | Failed err
95 instance Monad (MaybeErr err) where
96 return v = Succeeded v
97 Succeeded v >>= k = k v
98 Failed e >>= _ = Failed e
100 isSuccess :: MaybeErr err val -> Bool
101 isSuccess (Succeeded {}) = True
102 isSuccess (Failed {}) = False
104 failME :: err -> MaybeErr err val