{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}

-----------------------------------------------------------------------------
-- |
-- Module      :  Control.Monad
-- Copyright   :  (c) The University of Glasgow 2001
-- License     :  BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer  :  libraries@haskell.org
-- Stability   :  provisional
-- Portability :  portable
--
-- The 'Functor', 'Monad' and 'MonadPlus' classes,
-- with some useful operations on monads.

module Control.Monad
    (
    -- * Functor and monad classes

      Functor(fmap)
    , Monad((>>=), (>>), return)
    , MonadFail(fail)
    , MonadPlus(mzero, mplus)
    -- * Functions

    -- ** Naming conventions
    -- $naming

    -- ** Basic @Monad@ functions

    , mapM
    , mapM_
    , forM
    , forM_
    , sequence
    , sequence_
    , (=<<)
    , (>=>)
    , (<=<)
    , forever
    , void

    -- ** Generalisations of list functions

    , join
    , msum
    , mfilter
    , filterM
    , mapAndUnzipM
    , zipWithM
    , zipWithM_
    , foldM
    , foldM_
    , replicateM
    , replicateM_

    -- ** Conditional execution of monadic expressions

    , guard
    , when
    , unless

    -- ** Monadic lifting operators

    , liftM
    , liftM2
    , liftM3
    , liftM4
    , liftM5

    , ap

    -- ** Strict monadic functions

    , (<$!>)
    ) where

import Control.Monad.Fail ( MonadFail(fail) )
import Data.Foldable ( Foldable, sequence_, sequenceA_, msum, mapM_, foldlM, forM_ )
import Data.Functor ( void, (<$>) )
import Data.Traversable ( forM, mapM, traverse, sequence, sequenceA )

import GHC.Base hiding ( mapM, sequence )
import GHC.List ( zipWith, unzip )
import GHC.Num  ( (-) )

-- -----------------------------------------------------------------------------
-- Functions mandated by the Prelude

-- | Conditional failure of 'Alternative' computations. Defined by
--
-- @
-- guard True  = 'pure' ()
-- guard False = 'empty'
-- @
--
-- ==== __Examples__
--
-- Common uses of 'guard' include conditionally signaling an error in
-- an error monad and conditionally rejecting the current choice in an
-- 'Alternative'-based parser.
--
-- As an example of signaling an error in the error monad 'Maybe',
-- consider a safe division function @safeDiv x y@ that returns
-- 'Nothing' when the denominator @y@ is zero and @'Just' (x \`div\`
-- y)@ otherwise. For example:
--
-- @
-- >>> safeDiv 4 0
-- Nothing
-- >>> safeDiv 4 2
-- Just 2
-- @
--
-- A definition of @safeDiv@ using guards, but not 'guard':
--
-- @
-- safeDiv :: Int -> Int -> Maybe Int
-- safeDiv x y | y /= 0    = Just (x \`div\` y)
--             | otherwise = Nothing
-- @
--
-- A definition of @safeDiv@ using 'guard' and 'Monad' @do@-notation:
--
-- @
-- safeDiv :: Int -> Int -> Maybe Int
-- safeDiv x y = do
--   guard (y /= 0)
--   return (x \`div\` y)
-- @
guard           :: (Alternative f) => Bool -> f ()
guard :: Bool -> f ()
guard True      =  () -> f ()
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
guard False     =  f ()
forall (f :: * -> *) a. Alternative f => f a
empty

-- | This generalizes the list-based 'Data.List.filter' function.

{-# INLINE filterM #-}
filterM          :: (Applicative m) => (a -> m Bool) -> [a] -> m [a]
filterM :: (a -> m Bool) -> [a] -> m [a]
filterM p :: a -> m Bool
p        = (a -> m [a] -> m [a]) -> m [a] -> [a] -> m [a]
forall a b. (a -> b -> b) -> b -> [a] -> b
foldr (\ x :: a
x -> (Bool -> [a] -> [a]) -> m Bool -> m [a] -> m [a]
forall (f :: * -> *) a b c.
Applicative f =>
(a -> b -> c) -> f a -> f b -> f c
liftA2 (\ flg :: Bool
flg -> if Bool
flg then (a
xa -> [a] -> [a]
forall a. a -> [a] -> [a]
:) else [a] -> [a]
forall a. a -> a
id) (a -> m Bool
p a
x)) ([a] -> m [a]
forall (f :: * -> *) a. Applicative f => a -> f a
pure [])

infixr 1 <=<, >=>

-- | Left-to-right composition of Kleisli arrows.
(>=>)       :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)
f :: a -> m b
f >=> :: (a -> m b) -> (b -> m c) -> a -> m c
>=> g :: b -> m c
g     = \x :: a
x -> a -> m b
f a
x m b -> (b -> m c) -> m c
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= b -> m c
g

-- | Right-to-left composition of Kleisli arrows. @('>=>')@, with the arguments
-- flipped.
--
-- Note how this operator resembles function composition @('.')@:
--
-- > (.)   ::            (b ->   c) -> (a ->   b) -> a ->   c
-- > (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
(<=<)       :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c)
<=< :: (b -> m c) -> (a -> m b) -> a -> m c
(<=<)       = ((a -> m b) -> (b -> m c) -> a -> m c)
-> (b -> m c) -> (a -> m b) -> a -> m c
forall a b c. (a -> b -> c) -> b -> a -> c
flip (a -> m b) -> (b -> m c) -> a -> m c
forall (m :: * -> *) a b c.
Monad m =>
(a -> m b) -> (b -> m c) -> a -> m c
(>=>)

-- | Repeat an action indefinitely.
--
-- ==== __Examples__
--
-- A common use of 'forever' is to process input from network sockets,
-- 'System.IO.Handle's, and channels
-- (e.g. 'Control.Concurrent.MVar.MVar' and
-- 'Control.Concurrent.Chan.Chan').
--
-- For example, here is how we might implement an [echo
-- server](https://en.wikipedia.org/wiki/Echo_Protocol), using
-- 'forever' both to listen for client connections on a network socket
-- and to echo client input on client connection handles:
--
-- @
-- echoServer :: Socket -> IO ()
-- echoServer socket = 'forever' $ do
--   client <- accept socket
--   'Control.Concurrent.forkFinally' (echo client) (\\_ -> hClose client)
--   where
--     echo :: Handle -> IO ()
--     echo client = 'forever' $
--       hGetLine client >>= hPutStrLn client
-- @
forever     :: (Applicative f) => f a -> f b
{-# INLINE forever #-}
forever :: f a -> f b
forever a :: f a
a   = let a' :: f b
a' = f a
a f a -> f b -> f b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> f b
a' in f b
forall b. f b
a'
-- Use explicit sharing here, as it prevents a space leak regardless of
-- optimizations.

-- -----------------------------------------------------------------------------
-- Other monad functions

-- | The 'mapAndUnzipM' function maps its first argument over a list, returning
-- the result as a pair of lists. This function is mainly used with complicated
-- data structures or a state monad.
mapAndUnzipM      :: (Applicative m) => (a -> m (b,c)) -> [a] -> m ([b], [c])
{-# INLINE mapAndUnzipM #-}
mapAndUnzipM :: (a -> m (b, c)) -> [a] -> m ([b], [c])
mapAndUnzipM f :: a -> m (b, c)
f xs :: [a]
xs =  [(b, c)] -> ([b], [c])
forall a b. [(a, b)] -> ([a], [b])
unzip ([(b, c)] -> ([b], [c])) -> m [(b, c)] -> m ([b], [c])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (a -> m (b, c)) -> [a] -> m [(b, c)]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse a -> m (b, c)
f [a]
xs

-- | The 'zipWithM' function generalizes 'zipWith' to arbitrary applicative functors.
zipWithM          :: (Applicative m) => (a -> b -> m c) -> [a] -> [b] -> m [c]
{-# INLINE zipWithM #-}
zipWithM :: (a -> b -> m c) -> [a] -> [b] -> m [c]
zipWithM f :: a -> b -> m c
f xs :: [a]
xs ys :: [b]
ys  =  [m c] -> m [c]
forall (t :: * -> *) (f :: * -> *) a.
(Traversable t, Applicative f) =>
t (f a) -> f (t a)
sequenceA ((a -> b -> m c) -> [a] -> [b] -> [m c]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith a -> b -> m c
f [a]
xs [b]
ys)

-- | 'zipWithM_' is the extension of 'zipWithM' which ignores the final result.
zipWithM_         :: (Applicative m) => (a -> b -> m c) -> [a] -> [b] -> m ()
{-# INLINE zipWithM_ #-}
zipWithM_ :: (a -> b -> m c) -> [a] -> [b] -> m ()
zipWithM_ f :: a -> b -> m c
f xs :: [a]
xs ys :: [b]
ys =  [m c] -> m ()
forall (t :: * -> *) (f :: * -> *) a.
(Foldable t, Applicative f) =>
t (f a) -> f ()
sequenceA_ ((a -> b -> m c) -> [a] -> [b] -> [m c]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith a -> b -> m c
f [a]
xs [b]
ys)

{- | The 'foldM' function is analogous to 'Data.Foldable.foldl', except that its result is
encapsulated in a monad. Note that 'foldM' works from left-to-right over
the list arguments. This could be an issue where @('>>')@ and the `folded
function' are not commutative.


> foldM f a1 [x1, x2, ..., xm]
>
> ==
>
> do
>   a2 <- f a1 x1
>   a3 <- f a2 x2
>   ...
>   f am xm

If right-to-left evaluation is required, the input list should be reversed.

Note: 'foldM' is the same as 'foldlM'
-}

foldM          :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b
{-# INLINABLE foldM #-}
{-# SPECIALISE foldM :: (a -> b -> IO a) -> a -> [b] -> IO a #-}
{-# SPECIALISE foldM :: (a -> b -> Maybe a) -> a -> [b] -> Maybe a #-}
foldM :: (b -> a -> m b) -> b -> t a -> m b
foldM          = (b -> a -> m b) -> b -> t a -> m b
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM

-- | Like 'foldM', but discards the result.
foldM_         :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m ()
{-# INLINABLE foldM_ #-}
{-# SPECIALISE foldM_ :: (a -> b -> IO a) -> a -> [b] -> IO () #-}
{-# SPECIALISE foldM_ :: (a -> b -> Maybe a) -> a -> [b] -> Maybe () #-}
foldM_ :: (b -> a -> m b) -> b -> t a -> m ()
foldM_ f :: b -> a -> m b
f a :: b
a xs :: t a
xs  = (b -> a -> m b) -> b -> t a -> m b
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM b -> a -> m b
f b
a t a
xs m b -> m () -> m ()
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> m ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

{-
Note [Worker/wrapper transform on replicateM/replicateM_]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The implementations of replicateM and replicateM_ both leverage the
worker/wrapper transform. The simpler implementation of replicateM_, as an
example, would be:

    replicateM_ 0 _ = pure ()
    replicateM_ n f = f *> replicateM_ (n - 1) f

However, the self-recursive nature of this implementation inhibits inlining,
which means we never get to specialise to the action (`f` in the code above).
By contrast, the implementation below with a local loop makes it possible to
inline the entire definition (as happens for foldr, for example) thereby
specialising for the particular action.

For further information, see this Trac comment, which includes side-by-side
Core: https://ghc.haskell.org/trac/ghc/ticket/11795#comment:6
-}

-- | @'replicateM' n act@ performs the action @n@ times,
-- gathering the results.
replicateM        :: (Applicative m) => Int -> m a -> m [a]
{-# INLINABLE replicateM #-}
{-# SPECIALISE replicateM :: Int -> IO a -> IO [a] #-}
{-# SPECIALISE replicateM :: Int -> Maybe a -> Maybe [a] #-}
replicateM :: Int -> m a -> m [a]
replicateM cnt0 :: Int
cnt0 f :: m a
f =
    Int -> m [a]
forall t. (Ord t, Num t) => t -> m [a]
loop Int
cnt0
  where
    loop :: t -> m [a]
loop cnt :: t
cnt
        | t
cnt t -> t -> Bool
forall a. Ord a => a -> a -> Bool
<= 0  = [a] -> m [a]
forall (f :: * -> *) a. Applicative f => a -> f a
pure []
        | Bool
otherwise = (a -> [a] -> [a]) -> m a -> m [a] -> m [a]
forall (f :: * -> *) a b c.
Applicative f =>
(a -> b -> c) -> f a -> f b -> f c
liftA2 (:) m a
f (t -> m [a]
loop (t
cnt t -> t -> t
forall a. Num a => a -> a -> a
- 1))

-- | Like 'replicateM', but discards the result.
replicateM_       :: (Applicative m) => Int -> m a -> m ()
{-# INLINABLE replicateM_ #-}
{-# SPECIALISE replicateM_ :: Int -> IO a -> IO () #-}
{-# SPECIALISE replicateM_ :: Int -> Maybe a -> Maybe () #-}
replicateM_ :: Int -> m a -> m ()
replicateM_ cnt0 :: Int
cnt0 f :: m a
f =
    Int -> m ()
forall t. (Ord t, Num t) => t -> m ()
loop Int
cnt0
  where
    loop :: t -> m ()
loop cnt :: t
cnt
        | t
cnt t -> t -> Bool
forall a. Ord a => a -> a -> Bool
<= 0  = () -> m ()
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
        | Bool
otherwise = m a
f m a -> m () -> m ()
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> t -> m ()
loop (t
cnt t -> t -> t
forall a. Num a => a -> a -> a
- 1)


-- | The reverse of 'when'.
unless            :: (Applicative f) => Bool -> f () -> f ()
{-# INLINABLE unless #-}
{-# SPECIALISE unless :: Bool -> IO () -> IO () #-}
{-# SPECIALISE unless :: Bool -> Maybe () -> Maybe () #-}
unless :: Bool -> f () -> f ()
unless p :: Bool
p s :: f ()
s        =  if Bool
p then () -> f ()
forall (f :: * -> *) a. Applicative f => a -> f a
pure () else f ()
s

infixl 4 <$!>

-- | Strict version of 'Data.Functor.<$>'.
--
-- @since 4.8.0.0
(<$!>) :: Monad m => (a -> b) -> m a -> m b
{-# INLINE (<$!>) #-}
f :: a -> b
f <$!> :: (a -> b) -> m a -> m b
<$!> m :: m a
m = do
  a
x <- m a
m
  let z :: b
z = a -> b
f a
x
  b
z b -> m b -> m b
forall a b. a -> b -> b
`seq` b -> m b
forall (m :: * -> *) a. Monad m => a -> m a
return b
z


-- -----------------------------------------------------------------------------
-- Other MonadPlus functions

-- | Direct 'MonadPlus' equivalent of 'Data.List.filter'.
--
-- ==== __Examples__
--
-- The 'Data.List.filter' function is just 'mfilter' specialized to
-- the list monad:
--
-- @
-- 'Data.List.filter' = ( 'mfilter' :: (a -> Bool) -> [a] -> [a] )
-- @
--
-- An example using 'mfilter' with the 'Maybe' monad:
--
-- @
-- >>> mfilter odd (Just 1)
-- Just 1
-- >>> mfilter odd (Just 2)
-- Nothing
-- @
mfilter :: (MonadPlus m) => (a -> Bool) -> m a -> m a
{-# INLINABLE mfilter #-}
mfilter :: (a -> Bool) -> m a -> m a
mfilter p :: a -> Bool
p ma :: m a
ma = do
  a
a <- m a
ma
  if a -> Bool
p a
a then a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return a
a else m a
forall (m :: * -> *) a. MonadPlus m => m a
mzero

{- $naming

The functions in this library use the following naming conventions:

* A postfix \'@M@\' always stands for a function in the Kleisli category:
  The monad type constructor @m@ is added to function results
  (modulo currying) and nowhere else.  So, for example,

> filter  ::              (a ->   Bool) -> [a] ->   [a]
> filterM :: (Monad m) => (a -> m Bool) -> [a] -> m [a]

* A postfix \'@_@\' changes the result type from @(m a)@ to @(m ())@.
  Thus, for example:

> sequence  :: Monad m => [m a] -> m [a]
> sequence_ :: Monad m => [m a] -> m ()

* A prefix \'@m@\' generalizes an existing function to a monadic form.
  Thus, for example:

> filter  ::                (a -> Bool) -> [a] -> [a]
> mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a

-}