Allow nhc98 to cope with recent changes to Control.Exception.
[ghc-base.git] / Control / Monad.hs
1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
2 -----------------------------------------------------------------------------
3 -- |
4 -- Module      :  Control.Monad
5 -- Copyright   :  (c) The University of Glasgow 2001
6 -- License     :  BSD-style (see the file libraries/base/LICENSE)
7 -- 
8 -- Maintainer  :  libraries@haskell.org
9 -- Stability   :  provisional
10 -- Portability :  portable
11 --
12 -- The 'Functor', 'Monad' and 'MonadPlus' classes,
13 -- with some useful operations on monads.
14
15 module Control.Monad
16     (
17     -- * Functor and monad classes
18
19       Functor(fmap)
20     , Monad((>>=), (>>), return, fail)
21
22     , MonadPlus (   -- class context: Monad
23           mzero     -- :: (MonadPlus m) => m a
24         , mplus     -- :: (MonadPlus m) => m a -> m a -> m a
25         )
26     -- * Functions
27
28     -- ** Naming conventions
29     -- $naming
30
31     -- ** Basic @Monad@ functions
32
33     , mapM          -- :: (Monad m) => (a -> m b) -> [a] -> m [b]
34     , mapM_         -- :: (Monad m) => (a -> m b) -> [a] -> m ()
35     , forM          -- :: (Monad m) => [a] -> (a -> m b) -> m [b]
36     , forM_         -- :: (Monad m) => [a] -> (a -> m b) -> m ()
37     , sequence      -- :: (Monad m) => [m a] -> m [a]
38     , sequence_     -- :: (Monad m) => [m a] -> m ()
39     , (=<<)         -- :: (Monad m) => (a -> m b) -> m a -> m b
40     , (>=>)         -- :: (Monad m) => (a -> m b) -> (b -> m c) -> (a -> m c)
41     , (<=<)         -- :: (Monad m) => (b -> m c) -> (a -> m b) -> (a -> m c)
42     , forever       -- :: (Monad m) => m a -> m b
43     , void
44
45     -- ** Generalisations of list functions
46
47     , join          -- :: (Monad m) => m (m a) -> m a
48     , msum          -- :: (MonadPlus m) => [m a] -> m a
49     , filterM       -- :: (Monad m) => (a -> m Bool) -> [a] -> m [a]
50     , mapAndUnzipM  -- :: (Monad m) => (a -> m (b,c)) -> [a] -> m ([b], [c])
51     , zipWithM      -- :: (Monad m) => (a -> b -> m c) -> [a] -> [b] -> m [c]
52     , zipWithM_     -- :: (Monad m) => (a -> b -> m c) -> [a] -> [b] -> m ()
53     , foldM         -- :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a 
54     , foldM_        -- :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m ()
55     , replicateM    -- :: (Monad m) => Int -> m a -> m [a]
56     , replicateM_   -- :: (Monad m) => Int -> m a -> m ()
57
58     -- ** Conditional execution of monadic expressions
59
60     , guard         -- :: (MonadPlus m) => Bool -> m ()
61     , when          -- :: (Monad m) => Bool -> m () -> m ()
62     , unless        -- :: (Monad m) => Bool -> m () -> m ()
63
64     -- ** Monadic lifting operators
65
66     , liftM         -- :: (Monad m) => (a -> b) -> (m a -> m b)
67     , liftM2        -- :: (Monad m) => (a -> b -> c) -> (m a -> m b -> m c)
68     , liftM3        -- :: ...
69     , liftM4        -- :: ...
70     , liftM5        -- :: ...
71
72     , ap            -- :: (Monad m) => m (a -> b) -> m a -> m b
73
74     ) where
75
76 import Data.Maybe
77
78 #ifdef __GLASGOW_HASKELL__
79 import GHC.List
80 import GHC.Base
81 #endif
82
83 #ifdef __GLASGOW_HASKELL__
84 infixr 1 =<<
85
86 -- -----------------------------------------------------------------------------
87 -- Prelude monad functions
88
89 -- | Same as '>>=', but with the arguments interchanged.
90 {-# SPECIALISE (=<<) :: (a -> [b]) -> [a] -> [b] #-}
91 (=<<)           :: Monad m => (a -> m b) -> m a -> m b
92 f =<< x         = x >>= f
93
94 -- | Evaluate each action in the sequence from left to right,
95 -- and collect the results.
96 sequence       :: Monad m => [m a] -> m [a] 
97 {-# INLINE sequence #-}
98 sequence ms = foldr k (return []) ms
99             where
100               k m m' = do { x <- m; xs <- m'; return (x:xs) }
101
102 -- | Evaluate each action in the sequence from left to right,
103 -- and ignore the results.
104 sequence_        :: Monad m => [m a] -> m () 
105 {-# INLINE sequence_ #-}
106 sequence_ ms     =  foldr (>>) (return ()) ms
107
108 -- | @'mapM' f@ is equivalent to @'sequence' . 'map' f@.
109 mapM            :: Monad m => (a -> m b) -> [a] -> m [b]
110 {-# INLINE mapM #-}
111 mapM f as       =  sequence (map f as)
112
113 -- | @'mapM_' f@ is equivalent to @'sequence_' . 'map' f@.
114 mapM_           :: Monad m => (a -> m b) -> [a] -> m ()
115 {-# INLINE mapM_ #-}
116 mapM_ f as      =  sequence_ (map f as)
117
118 #endif  /* __GLASGOW_HASKELL__ */
119
120 -- -----------------------------------------------------------------------------
121 -- The MonadPlus class definition
122
123 -- | Monads that also support choice and failure.
124 class Monad m => MonadPlus m where
125    -- | the identity of 'mplus'.  It should also satisfy the equations
126    --
127    -- > mzero >>= f  =  mzero
128    -- > v >> mzero   =  mzero
129    --
130    mzero :: m a 
131    -- | an associative operation
132    mplus :: m a -> m a -> m a
133
134 instance MonadPlus [] where
135    mzero = []
136    mplus = (++)
137
138 instance MonadPlus Maybe where
139    mzero = Nothing
140
141    Nothing `mplus` ys  = ys
142    xs      `mplus` _ys = xs
143
144 -- -----------------------------------------------------------------------------
145 -- Functions mandated by the Prelude
146
147 -- | @'guard' b@ is @'return' ()@ if @b@ is 'True',
148 -- and 'mzero' if @b@ is 'False'.
149 guard           :: (MonadPlus m) => Bool -> m ()
150 guard True      =  return ()
151 guard False     =  mzero
152
153 -- | This generalizes the list-based 'filter' function.
154
155 filterM          :: (Monad m) => (a -> m Bool) -> [a] -> m [a]
156 filterM _ []     =  return []
157 filterM p (x:xs) =  do
158    flg <- p x
159    ys  <- filterM p xs
160    return (if flg then x:ys else ys)
161
162 -- | 'forM' is 'mapM' with its arguments flipped
163 forM            :: Monad m => [a] -> (a -> m b) -> m [b]
164 {-# INLINE forM #-}
165 forM            = flip mapM
166
167 -- | 'forM_' is 'mapM_' with its arguments flipped
168 forM_           :: Monad m => [a] -> (a -> m b) -> m ()
169 {-# INLINE forM_ #-}
170 forM_           = flip mapM_
171
172 -- | This generalizes the list-based 'concat' function.
173
174 msum        :: MonadPlus m => [m a] -> m a
175 {-# INLINE msum #-}
176 msum        =  foldr mplus mzero
177
178 infixr 1 <=<, >=>
179
180 -- | Left-to-right Kleisli composition of monads.
181 (>=>)       :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)
182 f >=> g     = \x -> f x >>= g
183
184 -- | Right-to-left Kleisli composition of monads. @('>=>')@, with the arguments flipped
185 (<=<)       :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c)
186 (<=<)       = flip (>=>)
187
188 -- | @'forever' act@ repeats the action infinitely.
189 forever     :: (Monad m) => m a -> m b
190 forever a   = a >> forever a
191
192 -- | @'void' value@ discards or ignores the result of evaluation, such as the return value of an 'IO' action.
193 void :: Functor f => f a -> f ()
194 void = fmap (const ())
195
196 -- -----------------------------------------------------------------------------
197 -- Other monad functions
198
199 -- | The 'join' function is the conventional monad join operator. It is used to
200 -- remove one level of monadic structure, projecting its bound argument into the
201 -- outer level.
202 join              :: (Monad m) => m (m a) -> m a
203 join x            =  x >>= id
204
205 -- | The 'mapAndUnzipM' function maps its first argument over a list, returning
206 -- the result as a pair of lists. This function is mainly used with complicated
207 -- data structures or a state-transforming monad.
208 mapAndUnzipM      :: (Monad m) => (a -> m (b,c)) -> [a] -> m ([b], [c])
209 mapAndUnzipM f xs =  sequence (map f xs) >>= return . unzip
210
211 -- | The 'zipWithM' function generalizes 'zipWith' to arbitrary monads.
212 zipWithM          :: (Monad m) => (a -> b -> m c) -> [a] -> [b] -> m [c]
213 zipWithM f xs ys  =  sequence (zipWith f xs ys)
214
215 -- | 'zipWithM_' is the extension of 'zipWithM' which ignores the final result.
216 zipWithM_         :: (Monad m) => (a -> b -> m c) -> [a] -> [b] -> m ()
217 zipWithM_ f xs ys =  sequence_ (zipWith f xs ys)
218
219 {- | The 'foldM' function is analogous to 'foldl', except that its result is
220 encapsulated in a monad. Note that 'foldM' works from left-to-right over
221 the list arguments. This could be an issue where @('>>')@ and the `folded
222 function' are not commutative.
223
224
225 >       foldM f a1 [x1, x2, ..., xm]
226
227 ==  
228
229 >       do
230 >         a2 <- f a1 x1
231 >         a3 <- f a2 x2
232 >         ...
233 >         f am xm
234
235 If right-to-left evaluation is required, the input list should be reversed.
236 -}
237
238 foldM             :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
239 foldM _ a []      =  return a
240 foldM f a (x:xs)  =  f a x >>= \fax -> foldM f fax xs
241
242 -- | Like 'foldM', but discards the result.
243 foldM_            :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m ()
244 foldM_ f a xs     = foldM f a xs >> return ()
245
246 -- | @'replicateM' n act@ performs the action @n@ times,
247 -- gathering the results.
248 replicateM        :: (Monad m) => Int -> m a -> m [a]
249 replicateM n x    = sequence (replicate n x)
250
251 -- | Like 'replicateM', but discards the result.
252 replicateM_       :: (Monad m) => Int -> m a -> m ()
253 replicateM_ n x   = sequence_ (replicate n x)
254
255 {- | Conditional execution of monadic expressions. For example, 
256
257 >       when debug (putStr "Debugging\n")
258
259 will output the string @Debugging\\n@ if the Boolean value @debug@ is 'True',
260 and otherwise do nothing.
261 -}
262
263 when              :: (Monad m) => Bool -> m () -> m ()
264 when p s          =  if p then s else return ()
265
266 -- | The reverse of 'when'.
267
268 unless            :: (Monad m) => Bool -> m () -> m ()
269 unless p s        =  if p then return () else s
270
271 -- | Promote a function to a monad.
272 liftM   :: (Monad m) => (a1 -> r) -> m a1 -> m r
273 liftM f m1              = do { x1 <- m1; return (f x1) }
274
275 -- | Promote a function to a monad, scanning the monadic arguments from
276 -- left to right.  For example,
277 --
278 -- >    liftM2 (+) [0,1] [0,2] = [0,2,1,3]
279 -- >    liftM2 (+) (Just 1) Nothing = Nothing
280 --
281 liftM2  :: (Monad m) => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r
282 liftM2 f m1 m2          = do { x1 <- m1; x2 <- m2; return (f x1 x2) }
283
284 -- | Promote a function to a monad, scanning the monadic arguments from
285 -- left to right (cf. 'liftM2').
286 liftM3  :: (Monad m) => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r
287 liftM3 f m1 m2 m3       = do { x1 <- m1; x2 <- m2; x3 <- m3; return (f x1 x2 x3) }
288
289 -- | Promote a function to a monad, scanning the monadic arguments from
290 -- left to right (cf. 'liftM2').
291 liftM4  :: (Monad m) => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r
292 liftM4 f m1 m2 m3 m4    = do { x1 <- m1; x2 <- m2; x3 <- m3; x4 <- m4; return (f x1 x2 x3 x4) }
293
294 -- | Promote a function to a monad, scanning the monadic arguments from
295 -- left to right (cf. 'liftM2').
296 liftM5  :: (Monad m) => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r
297 liftM5 f m1 m2 m3 m4 m5 = do { x1 <- m1; x2 <- m2; x3 <- m3; x4 <- m4; x5 <- m5; return (f x1 x2 x3 x4 x5) }
298
299 {- | In many situations, the 'liftM' operations can be replaced by uses of
300 'ap', which promotes function application. 
301
302 >       return f `ap` x1 `ap` ... `ap` xn
303
304 is equivalent to 
305
306 >       liftMn f x1 x2 ... xn
307
308 -}
309
310 ap                :: (Monad m) => m (a -> b) -> m a -> m b
311 ap                =  liftM2 id
312
313
314 {- $naming
315
316 The functions in this library use the following naming conventions: 
317
318 * A postfix \'@M@\' always stands for a function in the Kleisli category:
319   The monad type constructor @m@ is added to function results
320   (modulo currying) and nowhere else.  So, for example, 
321
322 >  filter  ::              (a ->   Bool) -> [a] ->   [a]
323 >  filterM :: (Monad m) => (a -> m Bool) -> [a] -> m [a]
324
325 * A postfix \'@_@\' changes the result type from @(m a)@ to @(m ())@.
326   Thus, for example: 
327
328 >  sequence  :: Monad m => [m a] -> m [a] 
329 >  sequence_ :: Monad m => [m a] -> m () 
330
331 * A prefix \'@m@\' generalizes an existing function to a monadic form.
332   Thus, for example: 
333
334 >  sum  :: Num a       => [a]   -> a
335 >  msum :: MonadPlus m => [m a] -> m a
336
337 -}