expectJust,
maybeToBool,
- thenMaybe, seqMaybe, returnMaybe, failMaybe, fmapMMaybe
+ MaybeT(..)
) where
import Data.Maybe
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
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
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}