HORIZON HASKELLDocslts/ghc-10.0.x8c2f8e82026-10-19Search names, modules, packages, or :: a typeCtrl K

GHC 10.0.0.20260917 · lts/ghc-10.0.x · 8c2f8e8 · 2026-10-19

Moduleprotolude-0.3.5Haskell2010

Protolude.Monad

  • 2 classes
  • 27 values
classclass Applicative m => Monad (m :: Type -> Type) where
#

The Monad class defines the basic operations over a monad, a concept from a branch of mathematics known as category theory. From the perspective of a Haskell programmer, however, it is best to think of a monad as an abstract datatype of actions. Haskell's do expressions provide a convenient syntax for writing monadic expressions.

Instances of Monad should satisfy the following:

Left identity

return a >>= k = k a

Right identity

m >>= return = m

Associativity

m >>= (\x -> k x >>= h) = (m >>= k) >>= h

Furthermore, the Monad and Applicative operations should relate as follows:

The above laws imply:

and that pure and (<*>) satisfy the applicative functor laws.

The instances of Monad for List, Maybe and System.IO.IO defined in the Prelude satisfy these laws.

Methods

  • (>>=) :: m a -> (a -> m b) -> m binfixl 1

    Sequentially compose two actions, passing any value produced by the first as an argument to the second.

    'as >>= bs' can be understood as the do expression

    do a <- as
       bs a
    

    An alternative name for this function is 'bind', because it is used to introduce bindings in monadic contexts, but some people may refer to it as 'flatMap', which results from it being equivalent to

    \x f -> join (fmap f x) :: Monad m => m a -> (a -> m b) -> m b

    which can be seen as mapping a value with Monad m => m a -> m (m b) and then 'flattening' m (m b) to m b using join.

  • return :: a -> m a

    Inject a value into the monadic type. This function should not be different from its default implementation as pure. The justification for the existence of this function is merely historic.

Instances75Monad, …
  • Monad ComplexDefined in base-4.23.0.0 · Data.Complex
  • Monad FirstDefined in base-4.23.0.0 · Data.Semigroup
  • Monad LastDefined in base-4.23.0.0 · Data.Semigroup
  • Monad MaxDefined in base-4.23.0.0 · Data.Semigroup
  • Monad MinDefined in base-4.23.0.0 · Data.Semigroup
  • Monad GetDefined in binary-0.8.9.3 · Data.Binary.Get.Internal
  • Monad PutMDefined in binary-0.8.9.3 · Data.Binary.Put
  • Monad PutDefined in bytestring-0.12.2.0 · Data.ByteString.Builder.Internal
  • Monad SeqDefined in containers-0.8 · Data.Sequence.Internal
  • Monad TreeDefined in containers-0.8 · Data.Tree
  • Monad PprMDefined in ghc-boot-th-10.0.0.20260917 · GHC.Boot.TH.PprLib
  • Monad NonEmptyDefined in ghc-internal-10.0.0 · GHC.Internal.Data.NonEmpty · orphan
  • Monad IdentityDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Functor.Identity
  • Monad FirstDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Monoid
  • Monad LastDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Monoid
  • Monad DownDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Ord
  • Monad DualDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Semigroup.Internal
  • Monad ProductDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Semigroup.Internal
  • Monad SumDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Semigroup.Internal
  • Monad NoIODefined in ghc-internal-10.0.0 · GHC.Internal.GHCi
  • Monad Par1Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Monad MaybeDefined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Monad STMDefined in ghc-internal-10.0.0 · GHC.Internal.STM
  • Monad QDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Monad
  • Monad PDefined in ghc-internal-10.0.0 · GHC.Internal.Text.ParserCombinators.ReadP
  • Monad ReadPDefined in ghc-internal-10.0.0 · GHC.Internal.Text.ParserCombinators.ReadP
  • Monad ReadPrecDefined in ghc-internal-10.0.0 · GHC.Internal.Text.ParserCombinators.ReadPrec
  • Monad SoloDefined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Monad IODefined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Monad STMDefined in stm-2.5.3.1 · Control.Sequential.STM
  • Monad []Defined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Monad ProxyDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Proxy
  • Monad U1Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Monad (State s)Defined in containers-0.8 · Utils.Containers.Internal.State
  • Monad (ST s)Defined in ghc-internal-10.0.0 · GHC.Internal.Control.Monad.ST.Lazy.Imp
  • Monad (Either e)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Either
  • Monad (ST s)Defined in ghc-internal-10.0.0 · GHC.Internal.ST
  • Monad (IParser t)Defined in text-2.1.4 · Data.Text.Internal.Read
  • Monad m => Monad (WrappedMonad m)Defined in base-4.23.0.0 · Control.Applicative
  • Monad m => Monad (CatchT m)Defined in exceptions-0.10.12 · Control.Monad.Catch.Pure
  • Monad m => Monad (MaybeT m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Maybe
  • Monoid a => Monad (Tuple2 a)Defined in ghc-internal-10.0.0 · GHC.Internal.Base
  • ArrowApply a => Monad (ArrowMonad a)Defined in ghc-internal-10.0.0 · GHC.Internal.Control.Arrow
  • Monad (t m) => Monad (LiftingAccum t m)Defined in mtl-2.3.2 · Control.Monad.Accum
  • Monad (t m) => Monad (LiftingSelect t m)Defined in mtl-2.3.2 · Control.Monad.Select
  • Monad f => Monad (Ap f)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Monoid
  • Monad f => Monad (Alt f)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Semigroup.Internal
  • Monad f => Monad (Rec1 f)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Monad m => Monad (Kleisli m a)Defined in ghc-internal-10.0.0 · GHC.Internal.Control.Arrow
  • Monad m => Monad (StateT s m)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Functor.Utils
  • Monad m => Monad (ExceptT e m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Except
  • Monad m => Monad (IdentityT m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Identity
  • Monad m => Monad (ReaderT r m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Reader
  • Monad m => Monad (SelectT r m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Select
  • Monad m => Monad (StateT s m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.State.Lazy
  • Monad m => Monad (StateT s m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.State.Strict
  • Monad m => Monad (WriterT w m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Writer.CPS
  • Monad m => Monad (Reverse m)Defined in transformers-0.6.3.0 · Data.Functor.Reverse

    Derived instance.

  • (Applicative f, Monad f) => Monad (WhenMissing f x)Defined in containers-0.8 · Data.IntMap.Internal

    Equivalent to ReaderT k (ReaderT x (MaybeT f)).

  • (Monoid a, Monoid b) => Monad (Tuple3 a b)Defined in ghc-internal-10.0.0 · GHC.Internal.Base
  • (Monoid w, Functor m, Monad m) => Monad (AccumT w m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Accum
  • (Monoid w, Monad m) => Monad (WriterT w m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Writer.Lazy
  • (Monoid w, Monad m) => Monad (WriterT w m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Writer.Strict
  • Monad (ContT r m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Cont
  • Monad ((->) r)Defined in ghc-internal-10.0.0 · GHC.Internal.Base
  • (Applicative f, Monad f) => Monad (WhenMissing f k x)Defined in containers-0.8 · Data.Map.Internal

    Equivalent to ReaderT k (ReaderT x (MaybeT f)) .

  • (Monad f, Applicative f) => Monad (WhenMatched f x y)Defined in containers-0.8 · Data.IntMap.Internal

    Equivalent to ReaderT Key (ReaderT x (ReaderT y (MaybeT f)))

  • (Monad f, Monad g) => Monad (Product f g)Defined in base-4.23.0.0 · Data.Functor.Product
  • (Monad f, Monad g) => Monad (f :*: g)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • (Monoid a, Monoid b, Monoid c) => Monad (Tuple4 a b c)Defined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Monad f => Monad (M1 i c f)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Monad m => Monad (RWST r w s m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.RWS.CPS
  • (Monad f, Applicative f) => Monad (WhenMatched f k x y)Defined in containers-0.8 · Data.Map.Internal

    Equivalent to ReaderT k (ReaderT x (ReaderT y (MaybeT f)))

  • (Monoid w, Monad m) => Monad (RWST r w s m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.RWS.Lazy
  • (Monoid w, Monad m) => Monad (RWST r w s m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.RWS.Strict
classclass (Alternative m, Monad m) => MonadPlus (m :: Type -> Type) where
#

Monads that also support choice and failure.

Methods

  • mzero :: m a

    The identity of mplus. It should also satisfy the equations

    mzero >>= f  =  mzero
    v >> mzero   =  mzero

    The default definition is

    mzero = empty
    
  • mplus :: m a -> m a -> m a

    An associative operation. The default definition is

    mplus = (<|>)
    
Instances35MonadPlus, …
value(=<<) :: Monad m => (a -> m b) -> m a -> m b
#

Same as >>=, but with the arguments interchanged.

as >>= f == f =<< as
value(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
#

Left-to-right composition of Kleisli arrows.

'(bs >=> cs) a' can be understood as the do expression

do b <- bs a
   cs b

or in terms of (>>=) as

bs a >>= cs
value(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
#

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
method(>>) :: m a -> m b -> m b
#

Sequentially compose two actions, discarding any value produced by the first, like sequencing operators (such as the semicolon) in imperative languages.

'as >> bs' can be understood as the do expression

do as
   bs

or in terms of (>>=) as

as >>= const bs
valueforever :: Applicative f => f a -> f b
#

Repeat an action indefinitely.

Examples

A common use of forever is to process input from network sockets, System.IO.Handles, and channels (e.g. MVar and Chan).

For example, here is how we might implement an echo server, 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
  forkFinally (echo client) (\_ -> hClose client)
  where
    echo :: Handle -> IO ()
    echo client = forever $
      hGetLine client >>= hPutStrLn client

Note that "forever" isn't necessarily non-terminating. If the action is in a MonadPlus and short-circuits after some number of iterations. then forever actually returns mzero, effectively short-circuiting its caller.

valuejoin :: Monad m => m (m a) -> m a
#

The join function is the conventional monad join operator. It is used to remove one level of monadic structure, projecting its bound argument into the outer level.

'join bss' can be understood as the do expression

do bs <- bss
   bs
Examples
Example1 expression
join [[1, 2, 3], [4, 5, 6], [7, 8, 9]][1,2,3,4,5,6,7,8,9]
Example1 expression
join (Just (Just 3))Just 3

A common use of join is to run an IO computation returned from an GHC.Conc.STM transaction, since GHC.Conc.STM transactions can't perform IO directly. Recall that

GHC.Internal.Conc.atomically :: STM a -> IO a

is used to run GHC.Conc.STM transactions atomically. So, by specializing the types of GHC.Internal.Conc.atomically and join to

GHC.Internal.Conc.atomically :: STM (IO b) -> IO (IO b)
join       :: IO (IO b)  -> IO b

we can compose them as

join . GHC.Internal.Conc.atomically :: STM (IO b) -> IO b

to run an GHC.Conc.STM transaction and the IO action it returns.

valuemfilter :: MonadPlus m => (a -> Bool) -> m a -> m a
#

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:

Example2 expressions
mfilter odd (Just 1)Just 1mfilter odd (Just 2)Nothing
valuefilterM :: Applicative m => (a -> m Bool) -> [a] -> m [a]
#

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

runIdentity (filterM (Identity . p) xs) == filter p xs
Examples
Example1 expression
filterM (\x -> do      putStrLn ("Keep: " ++ show x ++ "?")      answer <- getLine      pure (answer == "y"))    [1, 2, 3]Keep: 1?yKeep: 2?nKeep: 3?y[1,3]
Example1 expression
filterM (\x -> do      putStr (show x)      x' <- readLn      pure (x == x'))    [1, 2, 3]122233[2,3]
valuemapAndUnzipM :: Applicative m => (a -> m (b, c)) -> [a] -> m ([b], [c])
#

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.

valuefoldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b
#

The foldM function is analogous to 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

valuereplicateM :: Applicative m => Int -> m a -> m [a]
#

replicateM n act performs the action act n times, and then returns the list of results.

replicateM n (pure x) == pure (replicate n x)
Examples
Example1 expression
replicateM 3 getLinehiheyahiya["hi","heya","hiya"]
Example2 expressions
import Control.Monad.StaterunState (replicateM 3 $ state $ \s -> (s, s + 1)) 1([1,2,3],4)
valueguard :: Alternative f => Bool -> f ()
#

Conditional failure of Alternative computations. Defined by

guard True  = pure ()
guard False = empty
Examples

Common uses of guard include conditionally signalling an error in an error monad and conditionally rejecting the current choice in an Alternative-based parser.

As an example of signalling 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:

Example1 expression
safeDiv 4 0Nothing
Example1 expression
safeDiv 4 2Just 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)
valuewhen :: Applicative f => Bool -> f () -> f ()
#

Conditional execution of Applicative expressions. For example,

Examples
when debug (putStrLn "Debugging")

will output the string Debugging if the Boolean value debug is True, and otherwise do nothing.

Example1 expression
putStr "pi:" >> when False (print 3.14159)pi:
valueunless :: Applicative f => Bool -> f () -> f ()
#

The reverse of when.

Examples
Example1 expression
do x <- getLine       unless (x == "hi") (putStrLn "hi!")comingupwithexamplesisdifficulthi!
Example1 expression
unless (pi > exp 1) NothingJust ()
valueliftM :: Monad m => (a1 -> r) -> m a1 -> m r
#

Promote a function to a monad. This is equivalent to fmap but specialised to Monads.

This function can be used to define `fmap = liftM`, if Monad is already defined for a data type.

valueliftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r
#

Promote a function to a monad, scanning the monadic arguments from left to right.

This function can be used to define `liftA2 = liftM2`, if Monad is already defined for a data type.

Examples
Example1 expression
liftM2 (+) [0,1] [0,2][0,2,1,3]
Example1 expression
liftM2 (+) (Just 1) NothingNothing
Example1 expression
liftM2 (+) (+ 3) (* 2) 518
valueliftM3 :: Monad m => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r
#

Promote a function to a monad, scanning the monadic arguments from left to right (cf. liftM2).

valueliftM4
  1. :: Monad m
  2. => a1 -> a2 -> a3 -> a4 -> r
  3. -> m a1
  4. -> m a2
  5. -> m a3
  6. -> m a4
  7. -> m r
#

Promote a function to a monad, scanning the monadic arguments from left to right (cf. liftM2).

valueliftM5
  1. :: Monad m
  2. => a1 -> a2 -> a3 -> a4 -> a5 -> r
  3. -> m a1
  4. -> m a2
  5. -> m a3
  6. -> m a4
  7. -> m a5
  8. -> m r
#

Promote a function to a monad, scanning the monadic arguments from left to right (cf. liftM2).

valueliftM2' :: Monad m => (a -> b -> c) -> m a -> m b -> m c
#
valueap :: Monad m => m (a -> b) -> m a -> m b
#

In many situations, the liftM operations can be replaced by uses of ap, which promotes function application.

return f `ap` x1 `ap` ... `ap` xn

is equivalent to

liftM<n> f x1 x2 ... xn

This function can be used to define `(*) = ap`, if Monad is already defined for a data type.

Examples
Example1 expression
pure (\x y z -> x + y * z) `ap` Just 1 `ap` Just 5 `ap` Just 10Just 51
value(<$!>) :: Monad m => (a -> b) -> m a -> m b
#

Strict version of <$>.