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