| Copyright | (c) The University of Glasgow 2001 |
|---|---|
| License | BSD-style (see the file libraries/base/LICENSE) |
| Maintainer | libraries@haskell.org |
| Stability | provisional |
| Portability | portable |
| Safe Haskell | Trustworthy |
| Language | Haskell2010 |
Control.Monad
Contents
TheFunctor class is used for types that can be mapped over.Instances ofFunctor should satisfy the following laws:
fmap id == idfmap (f . g) == fmap f . fmap g
The instances ofFunctor for lists,Maybe andIOsatisfy these laws.
classApplicative m =>Monad mwhereSource#
TheMonad class defines the basic operations over amonad,a concept from a branch of mathematics known ascategory theory.From the perspective of a Haskell programmer, however, it is best tothink of a monad as anabstract datatype of actions.Haskell'sdo expressions provide a convenient syntax for writingmonadic expressions.
Instances ofMonad should satisfy the following laws:
Furthermore, theMonad andApplicative operations should relate as follows:
The above laws imply:
and thatpure and (<*>) satisfy the applicative functor laws.
The instances ofMonad for lists,Maybe andIOdefined in thePrelude satisfy these laws.
Minimal complete definition
Methods
(>>=) ::forall a b. m a -> (a -> m b) -> m binfixl 1Source#
Sequentially compose two actions, passing any value produced by the first as an argument to the second.
(>>) ::forall a b. m a -> m b -> m binfixl 1Source#
Sequentially compose two actions, discarding any value produced by the first, like sequencing operators (such as the semicolon) in imperative languages.
Inject a value into the monadic type.
Fail with a message. This operation is not part of the mathematical definition of a monad, but is invoked on pattern-match failure in ado expression.
As part of the MonadFail proposal (MFP), this function is moved to its own classMonadFail (seeControl.Monad.Fail for more details). The definition here will be removed in a future release.
class (Alternative m,Monad m) =>MonadPlus mwhereSource#
Monads that also support choice and failure.
Minimal complete definition
Nothing
Methods
The identity ofmplus. It should also satisfy the equations
mzero >>= f = mzerov >> mzero = mzero
The default definition is
mzero =emptymplus :: m a -> m a -> m aSource#
An associative operation. The default definition is
mplus = (<|>)| MonadPlus []Source# | Since: 2.1 |
| MonadPlusMaybeSource# | Since: 2.1 |
| MonadPlusIOSource# | Since: 4.9.0.0 |
| MonadPlusReadPSource# | Since: 2.1 |
| MonadPlusReadPrecSource# | Since: 2.1 |
| MonadPlusSTMSource# | Since: 4.3.0.0 |
| MonadPlusOptionSource# | Since: 4.9.0.0 |
| MonadPlus (U1 ::Type ->Type)Source# | Since: 4.9.0.0 |
| MonadPlus (Proxy ::Type ->Type)Source# | Since: 4.9.0.0 |
| (ArrowApply a,ArrowPlus a) =>MonadPlus (ArrowMonad a)Source# | Since: 4.6.0.0 |
Instance detailsDefined inControl.Arrow Methods mzero ::ArrowMonad a a0Source# mplus ::ArrowMonad a a0 ->ArrowMonad a a0 ->ArrowMonad a a0Source# | |
| MonadPlus f =>MonadPlus (Rec1 f)Source# | Since: 4.9.0.0 |
| MonadPlus f =>MonadPlus (Alt f)Source# | Since: 4.8.0.0 |
| MonadPlus f =>MonadPlus (Ap f)Source# | Since: 4.12.0.0 |
| (MonadPlus f,MonadPlus g) =>MonadPlus (f:*: g)Source# | Since: 4.9.0.0 |
| (MonadPlus f,MonadPlus g) =>MonadPlus (Product f g)Source# | Since: 4.9.0.0 |
| MonadPlus f =>MonadPlus (M1 i c f)Source# | Since: 4.9.0.0 |
The functions in this library use the following naming conventions:
M' always stands for a function in the Kleisli category: The monad type constructorm 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]
_' 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 ()
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
Monad functionsmapM :: (Traversable t,Monad m) => (a -> m b) -> t a -> m (t b)Source#
Map each element of a structure to a monadic action, evaluate these actions from left to right, and collect the results. For a version that ignores the results seemapM_.
forM :: (Traversable t,Monad m) => t a -> (a -> m b) -> m (t b)Source#
sequence :: (Traversable t,Monad m) => t (m a) -> m (t a)Source#
Evaluate each monadic action in the structure from left to right, and collect the results. For a version that ignores the results seesequence_.
sequence_ :: (Foldable t,Monad m) => t (m a) -> m ()Source#
Evaluate each monadic action in the structure from left to right, and ignore the results. For a version that doesn't ignore the results seesequence.
As of base 4.8.0.0,sequence_ is justsequenceA_, specialized toMonad.
(=<<) ::Monad m => (a -> m b) -> m a -> m binfixr 1Source#
Same as>>=, but with the arguments interchanged.
(>=>) ::Monad m => (a -> m b) -> (b -> m c) -> a -> m cinfixr 1Source#
Left-to-right composition of Kleisli arrows.
forever ::Applicative f => f a -> f bSource#
Repeat an action indefinitely.
A common use offorever is to process input from network sockets,Handles, and channels (e.g.MVar andChan).
For example, here is how we might implement anecho server, usingforever 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 socketforkFinally(echo client) (\_ -> hClose client) where echo :: Handle -> IO () echo client =forever$ hGetLine client >>= hPutStrLn client
void ::Functor f => f a -> f ()Source#
discards or ignores the result of evaluation, such as the return value of anvoid valueIO action.
Replace the contents of a with unit:MaybeInt
>>>void NothingNothing>>>void (Just 3)Just ()
Replace the contents of an with unit, resulting in anEitherIntInt:EitherInt '()'
>>>void (Left 8675309)Left 8675309>>>void (Right 8675309)Right ()
Replace every element of a list with unit:
>>>void [1,2,3][(),(),()]
Replace the second element of a pair with unit:
>>>void (1,2)(1,())
Discard the result of anIO action:
>>>mapM print [1,2]12[(),()]>>>void $ mapM print [1,2]12
join ::Monad m => m (m a) -> m aSource#
Thejoin 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.
A common use ofjoin is to run anIO computation returned from anSTM transaction, sinceSTM transactions can't performIO directly. Recall that
atomically :: STM a -> IO ais used to runSTM transactions atomically. So, by specializing the types ofatomically andjoin to
atomically:: STM (IO b) -> IO (IO b)join:: IO (IO b) -> IO b
we can compose them as
join.atomically:: STM (IO b) -> IO b
filterM ::Applicative m => (a -> mBool) -> [a] -> m [a]Source#
This generalizes the list-basedfilter function.
mapAndUnzipM ::Applicative m => (a -> m (b, c)) -> [a] -> m ([b], [c])Source#
ThemapAndUnzipM 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-transforming monad.
zipWithM ::Applicative m => (a -> b -> m c) -> [a] -> [b] -> m [c]Source#
zipWithM_ ::Applicative m => (a -> b -> m c) -> [a] -> [b] -> m ()Source#
foldM :: (Foldable t,Monad m) => (b -> a -> m b) -> b -> t a -> m bSource#
ThefoldM function is analogous tofoldl, except that its result isencapsulated in a monad. Note thatfoldM works from left-to-right overthe list arguments. This could be an issue where( and the `foldedfunction' 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.
foldM_ :: (Foldable t,Monad m) => (b -> a -> m b) -> b -> t a -> m ()Source#
LikefoldM, but discards the result.
replicateM ::Applicative m =>Int -> m a -> m [a]Source#
performs the actionreplicateM n actn times, gathering the results.
replicateM_ ::Applicative m =>Int -> m a -> m ()Source#
LikereplicateM, but discards the result.
guard ::Alternative f =>Bool -> f ()Source#
Conditional failure ofAlternative computations. Defined by
guard True =pure()guard False =empty
Common uses ofguard include conditionally signaling an error in an error monad and conditionally rejecting the current choice in anAlternative-based parser.
As an example of signaling an error in the error monadMaybe, consider a safe division functionsafeDiv x y that returnsNothing when the denominatory is zero and otherwise. For example:Just (x `div` y)
>>> safeDiv 4 0Nothing>>> safeDiv 4 2Just 2
A definition ofsafeDiv using guards, but notguard:
safeDiv :: Int -> Int -> Maybe IntsafeDiv x y | y /= 0 = Just (x `div` y) | otherwise = Nothing
A definition ofsafeDiv usingguard andMonaddo-notation:
safeDiv :: Int -> Int -> Maybe IntsafeDiv x y = do guard (y /= 0) return (x `div` y)
when ::Applicative f =>Bool -> f () -> f ()Source#
Conditional execution ofApplicative expressions. For example,
when debug (putStrLn "Debugging")
will output the stringDebugging if the Boolean valuedebug isTrue, and otherwise do nothing.
liftM2 ::Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m rSource#
Promote a function to a monad, scanning the monadic arguments from left to right. For example,
liftM2 (+) [0,1] [0,2] = [0,2,1,3]liftM2 (+) (Just 1) Nothing = Nothing
liftM3 ::Monad m => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m rSource#
Promote a function to a monad, scanning the monadic arguments from left to right (cf.liftM2).
liftM4 ::Monad m => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m rSource#
Promote a function to a monad, scanning the monadic arguments from left to right (cf.liftM2).
liftM5 ::Monad m => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m rSource#
Promote a function to a monad, scanning the monadic arguments from left to right (cf.liftM2).
Produced byHaddock version 2.20.0