2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
8 module Data.Maybe, -- Re-export all of Maybe
10 MaybeErr(..), -- Instance of Monad
20 thenMaybe, seqMaybe, returnMaybe, failMaybe, fmapMMaybe
23 #include "HsVersions.h"
30 %************************************************************************
32 \subsection[Maybe type]{The @Maybe@ type}
34 %************************************************************************
37 maybeToBool :: Maybe a -> Bool
38 maybeToBool Nothing = False
39 maybeToBool (Just x) = True
42 @catMaybes@ takes a list of @Maybe@s and returns a list of
43 the contents of all the @Just@s in it. @allMaybes@ collects
44 a list of @Justs@ into a single @Just@, returning @Nothing@ if there
48 allMaybes :: [Maybe a] -> Maybe [a]
49 allMaybes [] = Just []
50 allMaybes (Nothing : ms) = Nothing
51 allMaybes (Just x : ms) = case (allMaybes ms) of
53 Just xs -> Just (x:xs)
57 @firstJust@ takes a list of @Maybes@ and returns the
58 first @Just@ if there is one, or @Nothing@ otherwise.
61 firstJust :: [Maybe a] -> Maybe a
62 firstJust [] = Nothing
63 firstJust (Just x : ms) = Just x
64 firstJust (Nothing : ms) = firstJust ms
68 expectJust :: String -> Maybe a -> a
69 {-# INLINE expectJust #-}
70 expectJust err (Just x) = x
71 expectJust err Nothing = error ("expectJust " ++ err)
75 mapCatMaybes :: (a -> Maybe b) -> [a] -> [b]
76 mapCatMaybes f [] = []
77 mapCatMaybes f (x:xs) = case f x of
78 Just y -> y : mapCatMaybes f xs
79 Nothing -> mapCatMaybes f xs
85 seqMaybe :: Maybe a -> Maybe a -> Maybe a
86 seqMaybe (Just x) _ = Just x
87 seqMaybe Nothing my = my
89 thenMaybe :: Maybe a -> (a -> Maybe b) -> Maybe b
90 thenMaybe ma mb = case ma of
94 returnMaybe :: a -> Maybe a
100 orElse :: Maybe a -> a -> a
101 (Just x) `orElse` y = x
102 Nothing `orElse` y = y
104 fmapMMaybe :: Monad m => (a -> m b) -> Maybe a -> m (Maybe b)
105 fmapMMaybe f Nothing = return Nothing
106 fmapMMaybe f (Just x) = f x >>= \x' -> return (Just x')
111 %************************************************************************
113 \subsection[MaybeErr type]{The @MaybeErr@ type}
115 %************************************************************************
118 data MaybeErr err val = Succeeded val | Failed err
120 instance Monad (MaybeErr err) where
121 return v = Succeeded v
122 Succeeded v >>= k = k v
123 Failed e >>= k = Failed e
125 isSuccess :: MaybeErr err val -> Bool
126 isSuccess (Succeeded {}) = True
127 isSuccess (Failed {}) = False
129 failME :: err -> MaybeErr err val