X-Git-Url: http://git.megacz.com/?a=blobdiff_plain;f=compiler%2Futils%2FMaybes.lhs;h=8a6a5f441e2db9fc62b4345047c70d605984c803;hb=d436c70d43fb905c63220040168295e473f4b90a;hp=c977494d2b5f10d38d7e73504504470f0d1ad2c0;hpb=38ac36a32032a538db346411b119c47e4019c08f;p=ghc-hetmet.git diff --git a/compiler/utils/Maybes.lhs b/compiler/utils/Maybes.lhs index c977494..8a6a5f4 100644 --- a/compiler/utils/Maybes.lhs +++ b/compiler/utils/Maybes.lhs @@ -17,7 +17,7 @@ module Maybes ( expectJust, maybeToBool, - thenMaybe, seqMaybe, returnMaybe, failMaybe, fmapMMaybe + MaybeT(..) ) where import Data.Maybe @@ -35,14 +35,9 @@ infixr 4 `orElse` maybeToBool :: Maybe a -> Bool maybeToBool Nothing = False maybeToBool (Just _) = True -\end{code} - -@catMaybes@ takes a list of @Maybe@s and returns a list of -the contents of all the @Just@s in it. @allMaybes@ collects -a list of @Justs@ into a single @Just@, returning @Nothing@ if there -are any @Nothings@. -\begin{code} +-- | Collects a list of @Justs@ into a single @Just@, returning @Nothing@ if +-- there are any @Nothings@. allMaybes :: [Maybe a] -> Maybe [a] allMaybes [] = Just [] allMaybes (Nothing : _) = Nothing @@ -50,12 +45,8 @@ allMaybes (Just x : ms) = case allMaybes ms of Nothing -> Nothing Just xs -> Just (x:xs) -\end{code} - -@firstJust@ takes a list of @Maybes@ and returns the -first @Just@ if there is one, or @Nothing@ otherwise. - -\begin{code} +-- | Takes a list of @Maybes@ and returns the first @Just@ if there is one, or +-- @Nothing@ otherwise. firstJust :: [Maybe a] -> Maybe a firstJust [] = Nothing firstJust (Just x : _) = Just x @@ -77,31 +68,29 @@ mapCatMaybes f (x:xs) = case f x of Nothing -> mapCatMaybes f xs \end{code} -The Maybe monad -~~~~~~~~~~~~~~~ \begin{code} -seqMaybe :: Maybe a -> Maybe a -> Maybe a -seqMaybe (Just x) _ = Just x -seqMaybe Nothing my = my +orElse :: Maybe a -> a -> a +(Just x) `orElse` _ = x +Nothing `orElse` y = y +\end{code} -thenMaybe :: Maybe a -> (a -> Maybe b) -> Maybe b -thenMaybe ma mb = case ma of - Just x -> mb x - Nothing -> Nothing +%************************************************************************ +%* * +\subsection[MaybeT type]{The @MaybeT@ monad transformer} +%* * +%************************************************************************ -returnMaybe :: a -> Maybe a -returnMaybe = Just +\begin{code} -failMaybe :: Maybe a -failMaybe = Nothing +newtype MaybeT m a = MaybeT {runMaybeT :: m (Maybe a)} -orElse :: Maybe a -> a -> a -(Just x) `orElse` _ = x -Nothing `orElse` y = y +instance Functor m => Functor (MaybeT m) where + fmap f x = MaybeT $ fmap (fmap f) $ runMaybeT x -fmapMMaybe :: Monad m => (a -> m b) -> Maybe a -> m (Maybe b) -fmapMMaybe _ Nothing = return Nothing -fmapMMaybe f (Just x) = f x >>= \x' -> return (Just x') +instance Monad m => Monad (MaybeT m) where + return = MaybeT . return . Just + x >>= f = MaybeT $ runMaybeT x >>= maybe (return Nothing) (runMaybeT . f) + fail _ = MaybeT $ return Nothing \end{code}