base: Remove `Monad(fail)` method and reexport `MonadFail(fail)` instead
[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)
23 , MonadFail(fail)
24 , MonadPlus(mzero, mplus)
25 -- * Functions
26
27 -- ** Naming conventions
28 -- $naming
29
30 -- ** Basic @Monad@ functions
31
32 , mapM
33 , mapM_
34 , forM
35 , forM_
36 , sequence
37 , sequence_
38 , (=<<)
39 , (>=>)
40 , (<=<)
41 , forever
42 , void
43
44 -- ** Generalisations of list functions
45
46 , join
47 , msum
48 , mfilter
49 , filterM
50 , mapAndUnzipM
51 , zipWithM
52 , zipWithM_
53 , foldM
54 , foldM_
55 , replicateM
56 , replicateM_
57
58 -- ** Conditional execution of monadic expressions
59
60 , guard
61 , when
62 , unless
63
64 -- ** Monadic lifting operators
65
66 , liftM
67 , liftM2
68 , liftM3
69 , liftM4
70 , liftM5
71
72 , ap
73
74 -- ** Strict monadic functions
75
76 , (<$!>)
77 ) where
78
79 import Control.Monad.Fail ( MonadFail(fail) )
80 import Data.Foldable ( Foldable, sequence_, sequenceA_, msum, mapM_, foldlM, forM_ )
81 import Data.Functor ( void, (<$>) )
82 import Data.Traversable ( forM, mapM, traverse, sequence, sequenceA )
83
84 import GHC.Base hiding ( mapM, sequence )
85 import GHC.List ( zipWith, unzip )
86 import GHC.Num ( (-) )
87
88 -- -----------------------------------------------------------------------------
89 -- Functions mandated by the Prelude
90
91 -- | Conditional failure of 'Alternative' computations. Defined by
92 --
93 -- @
94 -- guard True = 'pure' ()
95 -- guard False = 'empty'
96 -- @
97 --
98 -- ==== __Examples__
99 --
100 -- Common uses of 'guard' include conditionally signaling an error in
101 -- an error monad and conditionally rejecting the current choice in an
102 -- 'Alternative'-based parser.
103 --
104 -- As an example of signaling an error in the error monad 'Maybe',
105 -- consider a safe division function @safeDiv x y@ that returns
106 -- 'Nothing' when the denominator @y@ is zero and @'Just' (x \`div\`
107 -- y)@ otherwise. For example:
108 --
109 -- @
110 -- >>> safeDiv 4 0
111 -- Nothing
112 -- >>> safeDiv 4 2
113 -- Just 2
114 -- @
115 --
116 -- A definition of @safeDiv@ using guards, but not 'guard':
117 --
118 -- @
119 -- safeDiv :: Int -> Int -> Maybe Int
120 -- safeDiv x y | y /= 0 = Just (x \`div\` y)
121 -- | otherwise = Nothing
122 -- @
123 --
124 -- A definition of @safeDiv@ using 'guard' and 'Monad' @do@-notation:
125 --
126 -- @
127 -- safeDiv :: Int -> Int -> Maybe Int
128 -- safeDiv x y = do
129 -- guard (y /= 0)
130 -- return (x \`div\` y)
131 -- @
132 guard :: (Alternative f) => Bool -> f ()
133 guard True = pure ()
134 guard False = empty
135
136 -- | This generalizes the list-based 'Data.List.filter' function.
137
138 {-# INLINE filterM #-}
139 filterM :: (Applicative m) => (a -> m Bool) -> [a] -> m [a]
140 filterM p = foldr (\ x -> liftA2 (\ flg -> if flg then (x:) else id) (p x)) (pure [])
141
142 infixr 1 <=<, >=>
143
144 -- | Left-to-right composition of Kleisli arrows.
145 (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)
146 f >=> g = \x -> f x >>= g
147
148 -- | Right-to-left composition of Kleisli arrows. @('>=>')@, with the arguments
149 -- flipped.
150 --
151 -- Note how this operator resembles function composition @('.')@:
152 --
153 -- > (.) :: (b -> c) -> (a -> b) -> a -> c
154 -- > (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
155 (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c)
156 (<=<) = flip (>=>)
157
158 -- | Repeat an action indefinitely.
159 --
160 -- ==== __Examples__
161 --
162 -- A common use of 'forever' is to process input from network sockets,
163 -- 'System.IO.Handle's, and channels
164 -- (e.g. 'Control.Concurrent.MVar.MVar' and
165 -- 'Control.Concurrent.Chan.Chan').
166 --
167 -- For example, here is how we might implement an [echo
168 -- server](https://en.wikipedia.org/wiki/Echo_Protocol), using
169 -- 'forever' both to listen for client connections on a network socket
170 -- and to echo client input on client connection handles:
171 --
172 -- @
173 -- echoServer :: Socket -> IO ()
174 -- echoServer socket = 'forever' $ do
175 -- client <- accept socket
176 -- 'Control.Concurrent.forkFinally' (echo client) (\\_ -> hClose client)
177 -- where
178 -- echo :: Handle -> IO ()
179 -- echo client = 'forever' $
180 -- hGetLine client >>= hPutStrLn client
181 -- @
182 forever :: (Applicative f) => f a -> f b
183 {-# INLINE forever #-}
184 forever a = let a' = a *> a' in a'
185 -- Use explicit sharing here, as it prevents a space leak regardless of
186 -- optimizations.
187
188 -- -----------------------------------------------------------------------------
189 -- Other monad functions
190
191 -- | The 'mapAndUnzipM' function maps its first argument over a list, returning
192 -- the result as a pair of lists. This function is mainly used with complicated
193 -- data structures or a state monad.
194 mapAndUnzipM :: (Applicative m) => (a -> m (b,c)) -> [a] -> m ([b], [c])
195 {-# INLINE mapAndUnzipM #-}
196 mapAndUnzipM f xs = unzip <$> traverse f xs
197
198 -- | The 'zipWithM' function generalizes 'zipWith' to arbitrary applicative functors.
199 zipWithM :: (Applicative m) => (a -> b -> m c) -> [a] -> [b] -> m [c]
200 {-# INLINE zipWithM #-}
201 zipWithM f xs ys = sequenceA (zipWith f xs ys)
202
203 -- | 'zipWithM_' is the extension of 'zipWithM' which ignores the final result.
204 zipWithM_ :: (Applicative m) => (a -> b -> m c) -> [a] -> [b] -> m ()
205 {-# INLINE zipWithM_ #-}
206 zipWithM_ f xs ys = sequenceA_ (zipWith f xs ys)
207
208 {- | The 'foldM' function is analogous to 'Data.Foldable.foldl', except that its result is
209 encapsulated in a monad. Note that 'foldM' works from left-to-right over
210 the list arguments. This could be an issue where @('>>')@ and the `folded
211 function' are not commutative.
212
213
214 > foldM f a1 [x1, x2, ..., xm]
215 >
216 > ==
217 >
218 > do
219 > a2 <- f a1 x1
220 > a3 <- f a2 x2
221 > ...
222 > f am xm
223
224 If right-to-left evaluation is required, the input list should be reversed.
225
226 Note: 'foldM' is the same as 'foldlM'
227 -}
228
229 foldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b
230 {-# INLINABLE foldM #-}
231 {-# SPECIALISE foldM :: (a -> b -> IO a) -> a -> [b] -> IO a #-}
232 {-# SPECIALISE foldM :: (a -> b -> Maybe a) -> a -> [b] -> Maybe a #-}
233 foldM = foldlM
234
235 -- | Like 'foldM', but discards the result.
236 foldM_ :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m ()
237 {-# INLINABLE foldM_ #-}
238 {-# SPECIALISE foldM_ :: (a -> b -> IO a) -> a -> [b] -> IO () #-}
239 {-# SPECIALISE foldM_ :: (a -> b -> Maybe a) -> a -> [b] -> Maybe () #-}
240 foldM_ f a xs = foldlM f a xs >> return ()
241
242 {-
243 Note [Worker/wrapper transform on replicateM/replicateM_]
244 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
245
246 The implementations of replicateM and replicateM_ both leverage the
247 worker/wrapper transform. The simpler implementation of replicateM_, as an
248 example, would be:
249
250 replicateM_ 0 _ = pure ()
251 replicateM_ n f = f *> replicateM_ (n - 1) f
252
253 However, the self-recursive nature of this implementation inhibits inlining,
254 which means we never get to specialise to the action (`f` in the code above).
255 By contrast, the implementation below with a local loop makes it possible to
256 inline the entire definition (as happens for foldr, for example) thereby
257 specialising for the particular action.
258
259 For further information, see this Trac comment, which includes side-by-side
260 Core: https://ghc.haskell.org/trac/ghc/ticket/11795#comment:6
261 -}
262
263 -- | @'replicateM' n act@ performs the action @n@ times,
264 -- gathering the results.
265 replicateM :: (Applicative m) => Int -> m a -> m [a]
266 {-# INLINABLE replicateM #-}
267 {-# SPECIALISE replicateM :: Int -> IO a -> IO [a] #-}
268 {-# SPECIALISE replicateM :: Int -> Maybe a -> Maybe [a] #-}
269 replicateM cnt0 f =
270 loop cnt0
271 where
272 loop cnt
273 | cnt <= 0 = pure []
274 | otherwise = liftA2 (:) f (loop (cnt - 1))
275
276 -- | Like 'replicateM', but discards the result.
277 replicateM_ :: (Applicative m) => Int -> m a -> m ()
278 {-# INLINABLE replicateM_ #-}
279 {-# SPECIALISE replicateM_ :: Int -> IO a -> IO () #-}
280 {-# SPECIALISE replicateM_ :: Int -> Maybe a -> Maybe () #-}
281 replicateM_ cnt0 f =
282 loop cnt0
283 where
284 loop cnt
285 | cnt <= 0 = pure ()
286 | otherwise = f *> loop (cnt - 1)
287
288
289 -- | The reverse of 'when'.
290 unless :: (Applicative f) => Bool -> f () -> f ()
291 {-# INLINABLE unless #-}
292 {-# SPECIALISE unless :: Bool -> IO () -> IO () #-}
293 {-# SPECIALISE unless :: Bool -> Maybe () -> Maybe () #-}
294 unless p s = if p then pure () else s
295
296 infixl 4 <$!>
297
298 -- | Strict version of 'Data.Functor.<$>'.
299 --
300 -- @since 4.8.0.0
301 (<$!>) :: Monad m => (a -> b) -> m a -> m b
302 {-# INLINE (<$!>) #-}
303 f <$!> m = do
304 x <- m
305 let z = f x
306 z `seq` return z
307
308
309 -- -----------------------------------------------------------------------------
310 -- Other MonadPlus functions
311
312 -- | Direct 'MonadPlus' equivalent of 'Data.List.filter'.
313 --
314 -- ==== __Examples__
315 --
316 -- The 'Data.List.filter' function is just 'mfilter' specialized to
317 -- the list monad:
318 --
319 -- @
320 -- 'Data.List.filter' = ( 'mfilter' :: (a -> Bool) -> [a] -> [a] )
321 -- @
322 --
323 -- An example using 'mfilter' with the 'Maybe' monad:
324 --
325 -- @
326 -- >>> mfilter odd (Just 1)
327 -- Just 1
328 -- >>> mfilter odd (Just 2)
329 -- Nothing
330 -- @
331 mfilter :: (MonadPlus m) => (a -> Bool) -> m a -> m a
332 {-# INLINABLE mfilter #-}
333 mfilter p ma = do
334 a <- ma
335 if p a then return a else mzero
336
337 {- $naming
338
339 The functions in this library use the following naming conventions:
340
341 * A postfix \'@M@\' always stands for a function in the Kleisli category:
342 The monad type constructor @m@ is added to function results
343 (modulo currying) and nowhere else. So, for example,
344
345 > filter :: (a -> Bool) -> [a] -> [a]
346 > filterM :: (Monad m) => (a -> m Bool) -> [a] -> m [a]
347
348 * A postfix \'@_@\' changes the result type from @(m a)@ to @(m ())@.
349 Thus, for example:
350
351 > sequence :: Monad m => [m a] -> m [a]
352 > sequence_ :: Monad m => [m a] -> m ()
353
354 * A prefix \'@m@\' generalizes an existing function to a monadic form.
355 Thus, for example:
356
357 > filter :: (a -> Bool) -> [a] -> [a]
358 > mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a
359
360 -}