Add Kleisli composition
[ghc-base.git] / Control / Monad.hs
1 {-# OPTIONS_GHC -fno-implicit-prelude #-}
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 functions from the "Prelude"
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 ()
43
44     -- ** Generalisations of list functions
45
46     , join          -- :: (Monad m) => m (m a) -> m a
47     , msum          -- :: (MonadPlus m) => [m a] -> m a
48     , filterM       -- :: (Monad m) => (a -> m Bool) -> [a] -> m [a]
49     , mapAndUnzipM  -- :: (Monad m) => (a -> m (b,c)) -> [a] -> m ([b], [c])
50     , zipWithM      -- :: (Monad m) => (a -> b -> m c) -> [a] -> [b] -> m [c]
51     , zipWithM_     -- :: (Monad m) => (a -> b -> m c) -> [a] -> [b] -> m ()
52     , foldM         -- :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a 
53     , foldM_        -- :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m ()
54     , replicateM    -- :: (Monad m) => Int -> m a -> m [a]
55     , replicateM_   -- :: (Monad m) => Int -> m a -> m ()
56
57     -- ** Conditional execution of monadic expressions
58
59     , guard         -- :: (MonadPlus m) => Bool -> m ()
60     , when          -- :: (Monad m) => Bool -> m () -> m ()
61     , unless        -- :: (Monad m) => Bool -> m () -> m ()
62
63     -- ** Monadic lifting operators
64
65     , liftM         -- :: (Monad m) => (a -> b) -> (m a -> m b)
66     , liftM2        -- :: (Monad m) => (a -> b -> c) -> (m a -> m b -> m c)
67     , liftM3        -- :: ...
68     , liftM4        -- :: ...
69     , liftM5        -- :: ...
70
71     , ap            -- :: (Monad m) => m (a -> b) -> m a -> m b
72
73     ) where
74
75 import Data.Maybe
76
77 #ifdef __GLASGOW_HASKELL__
78 import GHC.List
79 import GHC.Base
80 #endif
81
82 #ifdef __GLASGOW_HASKELL__
83 infixr 1 =<<
84
85 -- -----------------------------------------------------------------------------
86 -- Prelude monad functions
87
88 -- | Same as '>>=', but with the arguments interchanged.
89 {-# SPECIALISE (=<<) :: (a -> [b]) -> [a] -> [b] #-}
90 (=<<)           :: Monad m => (a -> m b) -> m a -> m b
91 f =<< x         = x >>= f
92
93 -- | Evaluate each action in the sequence from left to right,
94 -- and collect the results.
95 sequence       :: Monad m => [m a] -> m [a] 
96 {-# INLINE sequence #-}
97 sequence ms = foldr k (return []) ms
98             where
99               k m m' = do { x <- m; xs <- m'; return (x:xs) }
100
101 -- | Evaluate each action in the sequence from left to right,
102 -- and ignore the results.
103 sequence_        :: Monad m => [m a] -> m () 
104 {-# INLINE sequence_ #-}
105 sequence_ ms     =  foldr (>>) (return ()) ms
106
107 -- | @'mapM' f@ is equivalent to @'sequence' . 'map' f@.
108 mapM            :: Monad m => (a -> m b) -> [a] -> m [b]
109 {-# INLINE mapM #-}
110 mapM f as       =  sequence (map f as)
111
112 -- | @'mapM_' f@ is equivalent to @'sequence_' . 'map' f@.
113 mapM_           :: Monad m => (a -> m b) -> [a] -> m ()
114 {-# INLINE mapM_ #-}
115 mapM_ f as      =  sequence_ (map f as)
116
117 #endif  /* __GLASGOW_HASKELL__ */
118
119 -- -----------------------------------------------------------------------------
120 -- The MonadPlus class definition
121
122 -- | Monads that also support choice and failure.
123 class Monad m => MonadPlus m where
124    -- | the identity of 'mplus'.  It should also satisfy the equations
125    --
126    -- > mzero >>= f  =  mzero
127    -- > v >> mzero   =  mzero
128    --
129    -- (but the instance for 'System.IO.IO' defined in "Control.Monad.Error"
130    -- does not satisfy the second one).
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 ()
191 forever a   = a >> forever a
192
193 -- -----------------------------------------------------------------------------
194 -- Other monad functions
195
196 -- | The 'join' function is the conventional monad join operator. It is used to
197 -- remove one level of monadic structure, projecting its bound argument into the
198 -- outer level.
199 join              :: (Monad m) => m (m a) -> m a
200 join x            =  x >>= id
201
202 -- | The 'mapAndUnzipM' function maps its first argument over a list, returning
203 -- the result as a pair of lists. This function is mainly used with complicated
204 -- data structures or a state-transforming monad.
205 mapAndUnzipM      :: (Monad m) => (a -> m (b,c)) -> [a] -> m ([b], [c])
206 mapAndUnzipM f xs =  sequence (map f xs) >>= return . unzip
207
208 -- | The 'zipWithM' function generalizes 'zipWith' to arbitrary monads.
209 zipWithM          :: (Monad m) => (a -> b -> m c) -> [a] -> [b] -> m [c]
210 zipWithM f xs ys  =  sequence (zipWith f xs ys)
211
212 -- | 'zipWithM_' is the extension of 'zipWithM' which ignores the final result.
213 zipWithM_         :: (Monad m) => (a -> b -> m c) -> [a] -> [b] -> m ()
214 zipWithM_ f xs ys =  sequence_ (zipWith f xs ys)
215
216 {- | The 'foldM' function is analogous to 'foldl', except that its result is
217 encapsulated in a monad. Note that 'foldM' works from left-to-right over
218 the list arguments. This could be an issue where '(>>)' and the `folded
219 function' are not commutative.
220
221
222 >       foldM f a1 [x1, x2, ..., xm ]
223
224 ==  
225
226 >       do
227 >         a2 <- f a1 x1
228 >         a3 <- f a2 x2
229 >         ...
230 >         f am xm
231
232 If right-to-left evaluation is required, the input list should be reversed.
233 -}
234
235 foldM             :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
236 foldM _ a []      =  return a
237 foldM f a (x:xs)  =  f a x >>= \fax -> foldM f fax xs
238
239 -- | Like 'foldM', but discards the result.
240 foldM_            :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m ()
241 foldM_ f a xs     = foldM f a xs >> return ()
242
243 -- | @'replicateM' n act@ performs the action @n@ times,
244 -- gathering the results.
245 replicateM        :: (Monad m) => Int -> m a -> m [a]
246 replicateM n x    = sequence (replicate n x)
247
248 -- | Like 'replicateM', but discards the result.
249 replicateM_       :: (Monad m) => Int -> m a -> m ()
250 replicateM_ n x   = sequence_ (replicate n x)
251
252 {- | Conditional execution of monadic expressions. For example, 
253
254 >       when debug (putStr "Debugging\n")
255
256 will output the string @Debugging\\n@ if the Boolean value @debug@ is 'True',
257 and otherwise do nothing.
258 -}
259
260 when              :: (Monad m) => Bool -> m () -> m ()
261 when p s          =  if p then s else return ()
262
263 -- | The reverse of 'when'.
264
265 unless            :: (Monad m) => Bool -> m () -> m ()
266 unless p s        =  if p then return () else s
267
268 -- | Promote a function to a monad.
269 liftM   :: (Monad m) => (a1 -> r) -> m a1 -> m r
270 liftM f m1              = do { x1 <- m1; return (f x1) }
271
272 -- | Promote a function to a monad, scanning the monadic arguments from
273 -- left to right.  For example,
274 --
275 -- >    liftM2 (+) [0,1] [0,2] = [0,2,1,3]
276 -- >    liftM2 (+) (Just 1) Nothing = Nothing
277 --
278 liftM2  :: (Monad m) => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r
279 liftM2 f m1 m2          = do { x1 <- m1; x2 <- m2; return (f x1 x2) }
280
281 -- | Promote a function to a monad, scanning the monadic arguments from
282 -- left to right (cf. 'liftM2').
283 liftM3  :: (Monad m) => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r
284 liftM3 f m1 m2 m3       = do { x1 <- m1; x2 <- m2; x3 <- m3; return (f x1 x2 x3) }
285
286 -- | Promote a function to a monad, scanning the monadic arguments from
287 -- left to right (cf. 'liftM2').
288 liftM4  :: (Monad m) => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r
289 liftM4 f m1 m2 m3 m4    = do { x1 <- m1; x2 <- m2; x3 <- m3; x4 <- m4; return (f x1 x2 x3 x4) }
290
291 -- | Promote a function to a monad, scanning the monadic arguments from
292 -- left to right (cf. 'liftM2').
293 liftM5  :: (Monad m) => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r
294 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) }
295
296 {- | In many situations, the 'liftM' operations can be replaced by uses of
297 'ap', which promotes function application. 
298
299 >       return f `ap` x1 `ap` ... `ap` xn
300
301 is equivalent to 
302
303 >       liftMn f x1 x2 ... xn
304
305 -}
306
307 ap                :: (Monad m) => m (a -> b) -> m a -> m b
308 ap                =  liftM2 id
309
310
311 {- $naming
312
313 The functions in this library use the following naming conventions: 
314
315 * A postfix \'@M@\' always stands for a function in the Kleisli category:
316   The monad type constructor @m@ is added to function results
317   (modulo currying) and nowhere else.  So, for example, 
318
319 >  filter  ::              (a ->   Bool) -> [a] ->   [a]
320 >  filterM :: (Monad m) => (a -> m Bool) -> [a] -> m [a]
321
322 * A postfix \'@_@\' changes the result type from @(m a)@ to @(m ())@.
323   Thus, for example: 
324
325 >  sequence  :: Monad m => [m a] -> m [a] 
326 >  sequence_ :: Monad m => [m a] -> m () 
327
328 * A prefix \'@m@\' generalizes an existing function to a monadic form.
329   Thus, for example: 
330
331 >  sum  :: Num a       => [a]   -> a
332 >  msum :: MonadPlus m => [m a] -> m a
333
334 -}