9acb29c2707372011842c90d59c43387449e82b8
[ghc-base.git] / Control / Monad / List.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Control.Monad.List
4 -- Copyright   :  (c) Andy Gill 2001,
5 --                (c) Oregon Graduate Institute of Science and Technology, 2001
6 -- License     :  BSD-style (see the file libraries/base/LICENSE)
7 -- 
8 -- Maintainer  :  libraries@haskell.org
9 -- Stability   :  experimental
10 -- Portability :  non-portable (multi-parameter type classes)
11 --
12 -- The List monad.
13 --
14 -----------------------------------------------------------------------------
15
16 module Control.Monad.List (
17         ListT(..),
18         mapListT,
19         module Control.Monad,
20         module Control.Monad.Trans,
21   ) where
22
23 import Prelude
24
25 import Control.Monad
26 import Control.Monad.Trans
27 import Control.Monad.Reader
28 import Control.Monad.State
29 import Control.Monad.Cont
30 import Control.Monad.Error
31
32 -- ---------------------------------------------------------------------------
33 -- Our parameterizable list monad, with an inner monad
34
35 newtype ListT m a = ListT { runListT :: m [a] }
36
37 instance (Monad m) => Functor (ListT m) where
38         fmap f m = ListT $ do
39                 a <- runListT m
40                 return (map f a)
41
42 instance (Monad m) => Monad (ListT m) where
43         return a = ListT $ return [a]
44         m >>= k  = ListT $ do
45                 a <- runListT m
46                 b <- mapM (runListT . k) a
47                 return (concat b)
48         fail _ = ListT $ return []
49
50 instance (Monad m) => MonadPlus (ListT m) where
51         mzero       = ListT $ return []
52         m `mplus` n = ListT $ do
53                 a <- runListT m
54                 b <- runListT n
55                 return (a ++ b)
56
57 instance MonadTrans ListT where
58         lift m = ListT $ do
59                 a <- m
60                 return [a]
61
62 instance (MonadIO m) => MonadIO (ListT m) where
63         liftIO = lift . liftIO
64
65 instance (MonadReader s m) => MonadReader s (ListT m) where
66         ask       = lift ask
67         local f m = ListT $ local f (runListT m)
68
69 instance (MonadState s m) => MonadState s (ListT m) where
70         get = lift get
71         put = lift . put
72
73 instance (MonadCont m) => MonadCont (ListT m) where
74         callCC f = ListT $
75                 callCC $ \c ->
76                 runListT (f (\a -> ListT $ c [a]))
77
78 instance (MonadError e m) => MonadError e (ListT m) where
79         throwError       = lift . throwError
80         m `catchError` h = ListT $ runListT m
81                 `catchError` \e -> runListT (h e)
82
83 mapListT :: (m [a] -> n [b]) -> ListT m a -> ListT n b
84 mapListT f m = ListT $ f (runListT m)