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