X-Git-Url: http://git.megacz.com/?p=ghc-hetmet.git;a=blobdiff_plain;f=compiler%2Futils%2FMaybes.lhs;h=39e6185a19eedbc355a31573e951e5ac0f05994b;hp=1d43365dce467b2e9291027b75dd34f393c7ed85;hb=8133a9f47b99f4e65ed30551de32ad72c6b61b27;hpb=da6f25437e59e97791a1fea7ce2f9ce4dccc57f6 diff --git a/compiler/utils/Maybes.lhs b/compiler/utils/Maybes.lhs index 1d43365..39e6185 100644 --- a/compiler/utils/Maybes.lhs +++ b/compiler/utils/Maybes.lhs @@ -10,13 +10,15 @@ module Maybes ( MaybeErr(..), -- Instance of Monad failME, isSuccess, + fmapM_maybe, orElse, mapCatMaybes, allMaybes, - firstJust, + firstJust, firstJusts, expectJust, maybeToBool, + MaybeT(..) ) where import Data.Maybe @@ -34,14 +36,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 @@ -49,16 +46,14 @@ 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. +firstJust :: Maybe a -> Maybe a -> Maybe a +firstJust (Just a) _ = Just a +firstJust Nothing b = b -\begin{code} -firstJust :: [Maybe a] -> Maybe a -firstJust [] = Nothing -firstJust (Just x : _) = Just x -firstJust (Nothing : ms) = firstJust ms +-- | Takes a list of @Maybes@ and returns the first @Just@ if there is one, or +-- @Nothing@ otherwise. +firstJusts :: [Maybe a] -> Maybe a +firstJusts = foldr firstJust Nothing \end{code} \begin{code} @@ -77,11 +72,40 @@ mapCatMaybes f (x:xs) = case f x of \end{code} \begin{code} + orElse :: Maybe a -> a -> a (Just x) `orElse` _ = x Nothing `orElse` y = y \end{code} +\begin{code} +fmapM_maybe :: Monad m => (a -> m b) -> Maybe a -> m (Maybe b) +fmapM_maybe _ Nothing = return Nothing +fmapM_maybe f (Just x) = do + x' <- f x + return $ Just x' +\end{code} + +%************************************************************************ +%* * +\subsection[MaybeT type]{The @MaybeT@ monad transformer} +%* * +%************************************************************************ + +\begin{code} + +newtype MaybeT m a = MaybeT {runMaybeT :: m (Maybe a)} + +instance Functor m => Functor (MaybeT m) where + fmap f x = MaybeT $ fmap (fmap f) $ runMaybeT 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} + %************************************************************************ %* *