2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
15 module Data.Maybe, -- Re-export all of Maybe
17 MaybeErr(..), -- Instance of Monad
27 thenMaybe, seqMaybe, returnMaybe, failMaybe, fmapMMaybe
30 #include "HsVersions.h"
37 %************************************************************************
39 \subsection[Maybe type]{The @Maybe@ type}
41 %************************************************************************
44 maybeToBool :: Maybe a -> Bool
45 maybeToBool Nothing = False
46 maybeToBool (Just x) = True
49 @catMaybes@ takes a list of @Maybe@s and returns a list of
50 the contents of all the @Just@s in it. @allMaybes@ collects
51 a list of @Justs@ into a single @Just@, returning @Nothing@ if there
55 allMaybes :: [Maybe a] -> Maybe [a]
56 allMaybes [] = Just []
57 allMaybes (Nothing : ms) = Nothing
58 allMaybes (Just x : ms) = case (allMaybes ms) of
60 Just xs -> Just (x:xs)
64 @firstJust@ takes a list of @Maybes@ and returns the
65 first @Just@ if there is one, or @Nothing@ otherwise.
68 firstJust :: [Maybe a] -> Maybe a
69 firstJust [] = Nothing
70 firstJust (Just x : ms) = Just x
71 firstJust (Nothing : ms) = firstJust ms
75 expectJust :: String -> Maybe a -> a
76 {-# INLINE expectJust #-}
77 expectJust err (Just x) = x
78 expectJust err Nothing = error ("expectJust " ++ err)
82 mapCatMaybes :: (a -> Maybe b) -> [a] -> [b]
83 mapCatMaybes f [] = []
84 mapCatMaybes f (x:xs) = case f x of
85 Just y -> y : mapCatMaybes f xs
86 Nothing -> mapCatMaybes f xs
92 seqMaybe :: Maybe a -> Maybe a -> Maybe a
93 seqMaybe (Just x) _ = Just x
94 seqMaybe Nothing my = my
96 thenMaybe :: Maybe a -> (a -> Maybe b) -> Maybe b
97 thenMaybe ma mb = case ma of
101 returnMaybe :: a -> Maybe a
107 orElse :: Maybe a -> a -> a
108 (Just x) `orElse` y = x
109 Nothing `orElse` y = y
111 fmapMMaybe :: Monad m => (a -> m b) -> Maybe a -> m (Maybe b)
112 fmapMMaybe f Nothing = return Nothing
113 fmapMMaybe f (Just x) = f x >>= \x' -> return (Just x')
118 %************************************************************************
120 \subsection[MaybeErr type]{The @MaybeErr@ type}
122 %************************************************************************
125 data MaybeErr err val = Succeeded val | Failed err
127 instance Monad (MaybeErr err) where
128 return v = Succeeded v
129 Succeeded v >>= k = k v
130 Failed e >>= k = Failed e
132 isSuccess :: MaybeErr err val -> Bool
133 isSuccess (Succeeded {}) = True
134 isSuccess (Failed {}) = False
136 failME :: err -> MaybeErr err val