2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[Maybes]{The `Maybe' types and associated utility functions}
8 module Maybe, -- Re-export all of Maybe
10 MaybeErr(..), -- Instance of Monad
20 thenMaybe, seqMaybe, returnMaybe, failMaybe
23 #include "HsVersions.h"
31 %************************************************************************
33 \subsection[Maybe type]{The @Maybe@ type}
35 %************************************************************************
38 maybeToBool :: Maybe a -> Bool
39 maybeToBool Nothing = False
40 maybeToBool (Just x) = True
43 @catMaybes@ takes a list of @Maybe@s and returns a list of
44 the contents of all the @Just@s in it. @allMaybes@ collects
45 a list of @Justs@ into a single @Just@, returning @Nothing@ if there
49 allMaybes :: [Maybe a] -> Maybe [a]
50 allMaybes [] = Just []
51 allMaybes (Nothing : ms) = Nothing
52 allMaybes (Just x : ms) = case (allMaybes ms) of
54 Just xs -> Just (x:xs)
58 @firstJust@ takes a list of @Maybes@ and returns the
59 first @Just@ if there is one, or @Nothing@ otherwise.
62 firstJust :: [Maybe a] -> Maybe a
63 firstJust [] = Nothing
64 firstJust (Just x : ms) = Just x
65 firstJust (Nothing : ms) = firstJust ms
69 expectJust :: String -> Maybe a -> a
70 {-# INLINE expectJust #-}
71 expectJust err (Just x) = x
72 expectJust err Nothing = error ("expectJust " ++ err)
76 mapCatMaybes :: (a -> Maybe b) -> [a] -> [b]
77 mapCatMaybes f [] = []
78 mapCatMaybes f (x:xs) = case f x of
79 Just y -> y : mapCatMaybes f xs
80 Nothing -> mapCatMaybes f xs
86 seqMaybe :: Maybe a -> Maybe a -> Maybe a
87 seqMaybe (Just x) _ = Just x
88 seqMaybe Nothing my = my
90 thenMaybe :: Maybe a -> (a -> Maybe b) -> Maybe b
91 thenMaybe ma mb = case ma of
95 returnMaybe :: a -> Maybe a
101 orElse :: Maybe a -> a -> a
102 (Just x) `orElse` y = x
103 Nothing `orElse` y = y
107 %************************************************************************
109 \subsection[MaybeErr type]{The @MaybeErr@ type}
111 %************************************************************************
114 data MaybeErr err val = Succeeded val | Failed err
116 instance Monad (MaybeErr err) where
117 return v = Succeeded v
118 Succeeded v >>= k = k v
119 Failed e >>= k = Failed e
121 isSuccess :: MaybeErr err val -> Bool
122 isSuccess (Succeeded {}) = True
123 isSuccess (Failed {}) = False
125 failME :: err -> MaybeErr err val