4a8060f87c465a243a1cb352c13e15767443b636
[ghc.git] / libraries / base / Control / Monad.hs
1 {-# LANGUAGE Trustworthy #-}
2 {-# LANGUAGE NoImplicitPrelude #-}
3
4 -----------------------------------------------------------------------------
5 -- |
6 -- Module : Control.Monad
7 -- Copyright : (c) The University of Glasgow 2001
8 -- License : BSD-style (see the file libraries/base/LICENSE)
9 --
10 -- Maintainer : libraries@haskell.org
11 -- Stability : provisional
12 -- Portability : portable
13 --
14 -- The 'Functor', 'Monad' and 'MonadPlus' classes,
15 -- with some useful operations on monads.
16
17 module Control.Monad
18 (
19 -- * Functor and monad classes
20
21 Functor(fmap)
22 , Monad((>>=), (>>), return, fail)
23
24 , MonadPlus (
25 mzero
26 , mplus
27 )
28 -- * Functions
29
30 -- ** Naming conventions
31 -- $naming
32
33 -- ** Basic @Monad@ functions
34
35 , mapM
36 , mapM_
37 , forM
38 , forM_
39 , sequence
40 , sequence_
41 , (=<<)
42 , (>=>)
43 , (<=<)
44 , forever
45 , void
46
47 -- ** Generalisations of list functions
48
49 , join
50 , msum
51 , mfilter
52 , filterM
53 , mapAndUnzipM
54 , zipWithM
55 , zipWithM_
56 , foldM
57 , foldM_
58 , replicateM
59 , replicateM_
60
61 -- ** Conditional execution of monadic expressions
62
63 , guard
64 , when
65 , unless
66
67 -- ** Monadic lifting operators
68
69 , liftM
70 , liftM2
71 , liftM3
72 , liftM4
73 , liftM5
74
75 , ap
76
77 -- ** Strict monadic functions
78
79 , (<$!>)
80 ) where
81
82 import Data.Maybe
83
84 import GHC.List
85 import GHC.Base
86
87 infixr 1 =<<
88
89 -- -----------------------------------------------------------------------------
90 -- Prelude monad functions
91
92 -- | Same as '>>=', but with the arguments interchanged.
93 {-# SPECIALISE (=<<) :: (a -> [b]) -> [a] -> [b] #-}
94 (=<<) :: Monad m => (a -> m b) -> m a -> m b
95 f =<< x = x >>= f
96
97 -- | Evaluate each action in the sequence from left to right,
98 -- and collect the results.
99 sequence :: Monad m => [m a] -> m [a]
100 {-# INLINE sequence #-}
101 sequence ms = foldr k (return []) ms
102 where
103 k m m' = do { x <- m; xs <- m'; return (x:xs) }
104
105 -- | Evaluate each action in the sequence from left to right,
106 -- and ignore the results.
107 sequence_ :: Monad m => [m a] -> m ()
108 {-# INLINE sequence_ #-}
109 sequence_ ms = foldr (>>) (return ()) ms
110
111 -- | @'mapM' f@ is equivalent to @'sequence' . 'map' f@.
112 mapM :: Monad m => (a -> m b) -> [a] -> m [b]
113 {-# INLINE mapM #-}
114 mapM f as = sequence (map f as)
115
116 -- | @'mapM_' f@ is equivalent to @'sequence_' . 'map' f@.
117 mapM_ :: Monad m => (a -> m b) -> [a] -> m ()
118 {-# INLINE mapM_ #-}
119 mapM_ f as = sequence_ (map f as)
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 {-# INLINE forever #-}
192 forever a = let a' = a >> a' in a'
193 -- Use explicit sharing here, as it is prevents a space leak regardless of
194 -- optimizations.
195
196 -- | @'void' value@ discards or ignores the result of evaluation, such as the return value of an 'IO' action.
197 void :: Functor f => f a -> f ()
198 void = fmap (const ())
199
200 -- -----------------------------------------------------------------------------
201 -- Other monad functions
202
203 -- | The 'join' function is the conventional monad join operator. It is used to
204 -- remove one level of monadic structure, projecting its bound argument into the
205 -- outer level.
206 join :: (Monad m) => m (m a) -> m a
207 join x = x >>= id
208
209 -- | The 'mapAndUnzipM' function maps its first argument over a list, returning
210 -- the result as a pair of lists. This function is mainly used with complicated
211 -- data structures or a state-transforming monad.
212 mapAndUnzipM :: (Monad m) => (a -> m (b,c)) -> [a] -> m ([b], [c])
213 {-# INLINE mapAndUnzipM #-}
214 mapAndUnzipM f xs = sequence (map f xs) >>= return . unzip
215
216 -- | The 'zipWithM' function generalizes 'zipWith' to arbitrary monads.
217 zipWithM :: (Monad m) => (a -> b -> m c) -> [a] -> [b] -> m [c]
218 {-# INLINE zipWithM #-}
219 zipWithM f xs ys = sequence (zipWith f xs ys)
220
221 -- | 'zipWithM_' is the extension of 'zipWithM' which ignores the final result.
222 zipWithM_ :: (Monad m) => (a -> b -> m c) -> [a] -> [b] -> m ()
223 {-# INLINE zipWithM_ #-}
224 zipWithM_ f xs ys = sequence_ (zipWith f xs ys)
225
226 {- | The 'foldM' function is analogous to 'foldl', except that its result is
227 encapsulated in a monad. Note that 'foldM' works from left-to-right over
228 the list arguments. This could be an issue where @('>>')@ and the `folded
229 function' are not commutative.
230
231
232 > foldM f a1 [x1, x2, ..., xm]
233
234 ==
235
236 > do
237 > a2 <- f a1 x1
238 > a3 <- f a2 x2
239 > ...
240 > f am xm
241
242 If right-to-left evaluation is required, the input list should be reversed.
243 -}
244
245 foldM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
246 {-# INLINEABLE foldM #-}
247 {-# SPECIALISE foldM :: (a -> b -> IO a) -> a -> [b] -> IO a #-}
248 {-# SPECIALISE foldM :: (a -> b -> Maybe a) -> a -> [b] -> Maybe a #-}
249 foldM _ a [] = return a
250 foldM f a (x:xs) = f a x >>= \fax -> foldM f fax xs
251
252 -- | Like 'foldM', but discards the result.
253 foldM_ :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m ()
254 {-# INLINEABLE foldM_ #-}
255 {-# SPECIALISE foldM_ :: (a -> b -> IO a) -> a -> [b] -> IO () #-}
256 {-# SPECIALISE foldM_ :: (a -> b -> Maybe a) -> a -> [b] -> Maybe () #-}
257 foldM_ f a xs = foldM f a xs >> return ()
258
259 -- | @'replicateM' n act@ performs the action @n@ times,
260 -- gathering the results.
261 replicateM :: (Monad m) => Int -> m a -> m [a]
262 {-# INLINEABLE replicateM #-}
263 {-# SPECIALISE replicateM :: Int -> IO a -> IO [a] #-}
264 {-# SPECIALISE replicateM :: Int -> Maybe a -> Maybe [a] #-}
265 replicateM n x = sequence (replicate n x)
266
267 -- | Like 'replicateM', but discards the result.
268 replicateM_ :: (Monad m) => Int -> m a -> m ()
269 {-# INLINEABLE replicateM_ #-}
270 {-# SPECIALISE replicateM_ :: Int -> IO a -> IO () #-}
271 {-# SPECIALISE replicateM_ :: Int -> Maybe a -> Maybe () #-}
272 replicateM_ n x = sequence_ (replicate n x)
273
274 {- | Conditional execution of monadic expressions. For example,
275
276 > when debug (putStr "Debugging\n")
277
278 will output the string @Debugging\\n@ if the Boolean value @debug@ is 'True',
279 and otherwise do nothing.
280 -}
281
282 when :: (Monad m) => Bool -> m () -> m ()
283 {-# INLINEABLE when #-}
284 {-# SPECIALISE when :: Bool -> IO () -> IO () #-}
285 {-# SPECIALISE when :: Bool -> Maybe () -> Maybe () #-}
286 when p s = if p then s else return ()
287
288 -- | The reverse of 'when'.
289
290 unless :: (Monad m) => Bool -> m () -> m ()
291 {-# INLINEABLE unless #-}
292 {-# SPECIALISE unless :: Bool -> IO () -> IO () #-}
293 {-# SPECIALISE unless :: Bool -> Maybe () -> Maybe () #-}
294 unless p s = if p then return () else s
295
296 -- | Promote a function to a monad.
297 liftM :: (Monad m) => (a1 -> r) -> m a1 -> m r
298 liftM f m1 = do { x1 <- m1; return (f x1) }
299
300 -- | Promote a function to a monad, scanning the monadic arguments from
301 -- left to right. For example,
302 --
303 -- > liftM2 (+) [0,1] [0,2] = [0,2,1,3]
304 -- > liftM2 (+) (Just 1) Nothing = Nothing
305 --
306 liftM2 :: (Monad m) => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r
307 liftM2 f m1 m2 = do { x1 <- m1; x2 <- m2; return (f x1 x2) }
308
309 -- | Promote a function to a monad, scanning the monadic arguments from
310 -- left to right (cf. 'liftM2').
311 liftM3 :: (Monad m) => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r
312 liftM3 f m1 m2 m3 = do { x1 <- m1; x2 <- m2; x3 <- m3; return (f x1 x2 x3) }
313
314 -- | Promote a function to a monad, scanning the monadic arguments from
315 -- left to right (cf. 'liftM2').
316 liftM4 :: (Monad m) => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r
317 liftM4 f m1 m2 m3 m4 = do { x1 <- m1; x2 <- m2; x3 <- m3; x4 <- m4; return (f x1 x2 x3 x4) }
318
319 -- | Promote a function to a monad, scanning the monadic arguments from
320 -- left to right (cf. 'liftM2').
321 liftM5 :: (Monad m) => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r
322 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) }
323
324 {-# INLINEABLE liftM #-}
325 {-# SPECIALISE liftM :: (a1->r) -> IO a1 -> IO r #-}
326 {-# SPECIALISE liftM :: (a1->r) -> Maybe a1 -> Maybe r #-}
327 {-# INLINEABLE liftM2 #-}
328 {-# SPECIALISE liftM2 :: (a1->a2->r) -> IO a1 -> IO a2 -> IO r #-}
329 {-# SPECIALISE liftM2 :: (a1->a2->r) -> Maybe a1 -> Maybe a2 -> Maybe r #-}
330 {-# INLINEABLE liftM3 #-}
331 {-# SPECIALISE liftM3 :: (a1->a2->a3->r) -> IO a1 -> IO a2 -> IO a3 -> IO r #-}
332 {-# SPECIALISE liftM3 :: (a1->a2->a3->r) -> Maybe a1 -> Maybe a2 -> Maybe a3 -> Maybe r #-}
333 {-# INLINEABLE liftM4 #-}
334 {-# SPECIALISE liftM4 :: (a1->a2->a3->a4->r) -> IO a1 -> IO a2 -> IO a3 -> IO a4 -> IO r #-}
335 {-# SPECIALISE liftM4 :: (a1->a2->a3->a4->r) -> Maybe a1 -> Maybe a2 -> Maybe a3 -> Maybe a4 -> Maybe r #-}
336 {-# INLINEABLE liftM5 #-}
337 {-# SPECIALISE liftM5 :: (a1->a2->a3->a4->a5->r) -> IO a1 -> IO a2 -> IO a3 -> IO a4 -> IO a5 -> IO r #-}
338 {-# SPECIALISE liftM5 :: (a1->a2->a3->a4->a5->r) -> Maybe a1 -> Maybe a2 -> Maybe a3 -> Maybe a4 -> Maybe a5 -> Maybe r #-}
339
340 {- | In many situations, the 'liftM' operations can be replaced by uses of
341 'ap', which promotes function application.
342
343 > return f `ap` x1 `ap` ... `ap` xn
344
345 is equivalent to
346
347 > liftMn f x1 x2 ... xn
348
349 -}
350
351 ap :: (Monad m) => m (a -> b) -> m a -> m b
352 ap = liftM2 id
353
354 infixl 4 <$!>
355
356 -- | Strict version of 'Data.Functor.<$>'.
357 --
358 -- /Since: 4.7.1.0/
359 (<$!>) :: Monad m => (a -> b) -> m a -> m b
360 {-# INLINE (<$!>) #-}
361 f <$!> m = do
362 x <- m
363 let z = f x
364 z `seq` return z
365
366
367 -- -----------------------------------------------------------------------------
368 -- Other MonadPlus functions
369
370 -- | Direct 'MonadPlus' equivalent of 'filter'
371 -- @'filter'@ = @(mfilter:: (a -> Bool) -> [a] -> [a]@
372 -- applicable to any 'MonadPlus', for example
373 -- @mfilter odd (Just 1) == Just 1@
374 -- @mfilter odd (Just 2) == Nothing@
375
376 mfilter :: (MonadPlus m) => (a -> Bool) -> m a -> m a
377 {-# INLINEABLE mfilter #-}
378 mfilter p ma = do
379 a <- ma
380 if p a then return a else mzero
381
382 {- $naming
383
384 The functions in this library use the following naming conventions:
385
386 * A postfix \'@M@\' always stands for a function in the Kleisli category:
387 The monad type constructor @m@ is added to function results
388 (modulo currying) and nowhere else. So, for example,
389
390 > filter :: (a -> Bool) -> [a] -> [a]
391 > filterM :: (Monad m) => (a -> m Bool) -> [a] -> m [a]
392
393 * A postfix \'@_@\' changes the result type from @(m a)@ to @(m ())@.
394 Thus, for example:
395
396 > sequence :: Monad m => [m a] -> m [a]
397 > sequence_ :: Monad m => [m a] -> m ()
398
399 * A prefix \'@m@\' generalizes an existing function to a monadic form.
400 Thus, for example:
401
402 > sum :: Num a => [a] -> a
403 > msum :: MonadPlus m => [m a] -> m a
404
405 -}