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