PageRenderTime 72ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/libraries/base/Control/Monad.hs

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