Copyright | (c) 2016 Stephen Diehl (c) 2016-2018 Serokell (c) 2018-2023 Kowainik |
---|---|
License | MIT |
Maintainer | Kowainik <xrom.xkov@gmail.com> |
Stability | Stable |
Portability | Portable |
Safe Haskell | Safe |
Language | Haskell2010 |
Reexports functions to work with monads.
Synopsis
- newtype ExceptT e (m :: Type -> Type) a = ExceptT (m (Either e a))
- runExceptT :: ExceptT e m a -> m (Either e a)
- newtype ReaderT r (m :: Type -> Type) a = ReaderT {
- runReaderT :: r -> m a
- type Reader r = ReaderT r Identity
- class Monad m => MonadReader r (m :: Type -> Type) | m -> r where
- runReader :: Reader r a -> r -> a
- withReader :: (r' -> r) -> Reader r a -> Reader r' a
- withReaderT :: forall r' r (m :: Type -> Type) a. (r' -> r) -> ReaderT r m a -> ReaderT r' m a
- asks :: MonadReader r m => (r -> a) -> m a
- newtype StateT s (m :: Type -> Type) a = StateT {
- runStateT :: s -> m (a, s)
- type State s = StateT s Identity
- class Monad m => MonadState s (m :: Type -> Type) | m -> s where
- runState :: State s a -> s -> (a, s)
- execState :: State s a -> s -> s
- evalState :: State s a -> s -> a
- withState :: (s -> s) -> State s a -> State s a
- evalStateT :: Monad m => StateT s m a -> s -> m a
- execStateT :: Monad m => StateT s m a -> s -> m s
- modify :: MonadState s m => (s -> s) -> m ()
- modify' :: MonadState s m => (s -> s) -> m ()
- gets :: MonadState s m => (s -> a) -> m a
- class Monad m => MonadIO (m :: Type -> Type) where
- class (forall (m :: Type -> Type). Monad m => Monad (t m)) => MonadTrans (t :: (Type -> Type) -> Type -> Type) where
- data IdentityT (f :: k -> Type) (a :: k)
- newtype MaybeT (m :: Type -> Type) a = MaybeT {}
- maybeToExceptT :: forall (m :: Type -> Type) e a. Functor m => e -> MaybeT m a -> ExceptT e m a
- exceptToMaybeT :: forall (m :: Type -> Type) e a. Functor m => ExceptT e m a -> MaybeT m a
- class (Alternative m, Monad m) => MonadPlus (m :: Type -> Type) where
- class Applicative m => Monad (m :: Type -> Type) where
- forever :: Applicative f => f a -> f b
- join :: Monad m => m (m a) -> m a
- (=<<) :: Monad m => (a -> m b) -> m a -> m b
- filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a]
- (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
- (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
- mapAndUnzipM :: Applicative m => (a -> m (b, c)) -> [a] -> m ([b], [c])
- zipWithM :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m [c]
- zipWithM_ :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m ()
- replicateM :: Applicative m => Int -> m a -> m [a]
- replicateM_ :: Applicative m => Int -> m a -> m ()
- (<$!>) :: Monad m => (a -> b) -> m a -> m b
- mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a
- class Monad m => MonadFail (m :: Type -> Type) where
- data Maybe a
- maybe :: b -> (a -> b) -> Maybe a -> b
- isJust :: Maybe a -> Bool
- isNothing :: Maybe a -> Bool
- fromMaybe :: a -> Maybe a -> a
- maybeToList :: Maybe a -> [a]
- listToMaybe :: [a] -> Maybe a
- catMaybes :: [Maybe a] -> [a]
- mapMaybe :: (a -> Maybe b) -> [a] -> [b]
- data Either a b
- either :: (a -> c) -> (b -> c) -> Either a b -> c
- lefts :: [Either a b] -> [a]
- rights :: [Either a b] -> [b]
- partitionEithers :: [Either a b] -> ([a], [b])
- isLeft :: Either a b -> Bool
- isRight :: Either a b -> Bool
Reexport transformers
newtype ExceptT e (m :: Type -> Type) a #
A monad transformer that adds exceptions to other monads.
ExceptT
constructs a monad parameterized over two things:
- e - The exception type.
- m - The inner monad.
The return
function yields a computation that produces the given
value, while >>=
sequences two subcomputations, exiting on the
first exception.
Instances
runExceptT :: ExceptT e m a -> m (Either e a) #
The inverse of ExceptT
.
newtype ReaderT r (m :: Type -> Type) a #
The reader monad transformer, which adds a read-only environment to the given monad.
The return
function ignores the environment, while >>=
passes
the inherited environment to both subcomputations.
ReaderT | |
|
Instances
type Reader r = ReaderT r Identity #
The parameterizable reader monad.
Computations are functions of a shared environment.
The return
function ignores the environment, while >>=
passes
the inherited environment to both subcomputations.
class Monad m => MonadReader r (m :: Type -> Type) | m -> r where #
See examples in Control.Monad.Reader.
Note, the partially applied function type (->) r
is a simple reader monad.
See the instance
declaration below.
Retrieves the monad environment.
:: (r -> r) | The function to modify the environment. |
-> m a |
|
-> m a |
Executes a computation in a modified environment.
:: (r -> a) | The selector function to apply to the environment. |
-> m a |
Retrieves a function of the current environment.
Instances
MonadReader r m => MonadReader r (MaybeT m) | |
(Monoid w, MonadReader r m) => MonadReader r (AccumT w m) | Since: mtl-2.3 |
MonadReader r m => MonadReader r (ExceptT e m) | Since: mtl-2.2 |
MonadReader r m => MonadReader r (IdentityT m) | |
Monad m => MonadReader r (ReaderT r m) | |
MonadReader r m => MonadReader r (StateT s m) | |
MonadReader r m => MonadReader r (StateT s m) | |
(Monoid w, MonadReader r m) => MonadReader r (WriterT w m) | Since: mtl-2.3 |
(Monoid w, MonadReader r m) => MonadReader r (WriterT w m) | |
(Monoid w, MonadReader r m) => MonadReader r (WriterT w m) | |
MonadReader r' m => MonadReader r' (SelectT r m) | Since: mtl-2.3 |
MonadReader r ((->) r) | |
MonadReader r' m => MonadReader r' (ContT r m) | |
(Monad m, Monoid w) => MonadReader r (RWST r w s m) | Since: mtl-2.3 |
(Monad m, Monoid w) => MonadReader r (RWST r w s m) | |
(Monad m, Monoid w) => MonadReader r (RWST r w s m) | |
:: Reader r a | A |
-> r | An initial environment. |
-> a |
Runs a Reader
and extracts the final value from it.
(The inverse of reader
.)
:: (r' -> r) | The function to modify the environment. |
-> Reader r a | Computation to run in the modified environment. |
-> Reader r' a |
Execute a computation in a modified environment
(a specialization of withReaderT
).
runReader
(withReader
f m) =runReader
m . f
:: forall r' r (m :: Type -> Type) a. (r' -> r) | The function to modify the environment. |
-> ReaderT r m a | Computation to run in the modified environment. |
-> ReaderT r' m a |
Execute a computation in a modified environment
(a more general version of local
).
runReaderT
(withReaderT
f m) =runReaderT
m . f
:: MonadReader r m | |
=> (r -> a) | The selector function to apply to the environment. |
-> m a |
Retrieves a function of the current environment.
newtype StateT s (m :: Type -> Type) a #
A state transformer monad parameterized by:
s
- The state.m
- The inner monad.
The return
function leaves the state unchanged, while >>=
uses
the final state of the first computation as the initial state of
the second.
Instances
MonadReader r m => MonadReader r (StateT s m) | |
Monad m => MonadState s (StateT s m) | |
MonadTrans (StateT s) | |
Defined in Control.Monad.Trans.State.Strict | |
MonadFail m => MonadFail (StateT s m) | |
Defined in Control.Monad.Trans.State.Strict | |
MonadFix m => MonadFix (StateT s m) | |
Defined in Control.Monad.Trans.State.Strict | |
MonadIO m => MonadIO (StateT s m) | |
Defined in Control.Monad.Trans.State.Strict | |
Contravariant m => Contravariant (StateT s m) | |
(Functor m, MonadPlus m) => Alternative (StateT s m) | |
(Functor m, Monad m) => Applicative (StateT s m) | |
Defined in Control.Monad.Trans.State.Strict | |
Functor m => Functor (StateT s m) | |
Monad m => Monad (StateT s m) | |
MonadPlus m => MonadPlus (StateT s m) | |
Generic (StateT s m a) | |
type Rep (StateT s m a) | |
Defined in Control.Monad.Trans.State.Strict |
type State s = StateT s Identity #
A state monad parameterized by the type s
of the state to carry.
The return
function leaves the state unchanged, while >>=
uses
the final state of the first computation as the initial state of
the second.
class Monad m => MonadState s (m :: Type -> Type) | m -> s where #
Minimal definition is either both of get
and put
or just state
Return the state from the internals of the monad.
Replace the state inside the monad.
state :: (s -> (a, s)) -> m a #
Embed a simple state action into the monad.
Instances
MonadState s m => MonadState s (MaybeT m) | |
(Monoid w, MonadState s m) => MonadState s (AccumT w m) | Since: mtl-2.3 |
MonadState s m => MonadState s (ExceptT e m) | Since: mtl-2.2 |
MonadState s m => MonadState s (IdentityT m) | |
MonadState s m => MonadState s (ReaderT r m) | |
MonadState s m => MonadState s (SelectT r m) | Since: mtl-2.3 |
Monad m => MonadState s (StateT s m) | |
Monad m => MonadState s (StateT s m) | |
(Monoid w, MonadState s m) => MonadState s (WriterT w m) | Since: mtl-2.3 |
(Monoid w, MonadState s m) => MonadState s (WriterT w m) | |
(Monoid w, MonadState s m) => MonadState s (WriterT w m) | |
MonadState s m => MonadState s (ContT r m) | |
(Monad m, Monoid w) => MonadState s (RWST r w s m) | Since: mtl-2.3 |
(Monad m, Monoid w) => MonadState s (RWST r w s m) | |
(Monad m, Monoid w) => MonadState s (RWST r w s m) | |
:: State s a | state-passing computation to execute |
-> s | initial state |
-> (a, s) | return value and final state |
Unwrap a state monad computation as a function.
(The inverse of state
.)
:: State s a | state-passing computation to execute |
-> s | initial value |
-> s | final state |
:: State s a | state-passing computation to execute |
-> s | initial value |
-> a | return value of the state computation |
evalStateT :: Monad m => StateT s m a -> s -> m a #
Evaluate a state computation with the given initial state and return the final value, discarding the final state.
evalStateT
m s =liftM
fst
(runStateT
m s)
execStateT :: Monad m => StateT s m a -> s -> m s #
Evaluate a state computation with the given initial state and return the final state, discarding the final value.
execStateT
m s =liftM
snd
(runStateT
m s)
modify :: MonadState s m => (s -> s) -> m () #
Monadic state transformer.
Maps an old state to a new state inside a state monad. The old state is thrown away.
Main> :t modify ((+1) :: Int -> Int) modify (...) :: (MonadState Int a) => a ()
This says that modify (+1)
acts over any
Monad that is a member of the MonadState
class,
with an Int
state.
modify' :: MonadState s m => (s -> s) -> m () #
A variant of modify
in which the computation is strict in the
new state.
Since: mtl-2.2
gets :: MonadState s m => (s -> a) -> m a #
Gets specific component of the state, using a projection function supplied.
class Monad m => MonadIO (m :: Type -> Type) where #
Monads in which IO
computations may be embedded.
Any monad built by applying a sequence of monad transformers to the
IO
monad will be an instance of this class.
Instances should satisfy the following laws, which state that liftIO
is a transformer of monads:
Lift a computation from the IO
monad.
This allows us to run IO computations in any monadic stack, so long as it supports these kinds of operations
(i.e. IO
is the base monad for the stack).
Example
import Control.Monad.Trans.State -- from the "transformers" library printState :: Show s => StateT s IO () printState = do state <- get liftIO $ print state
Had we omitted
, we would have ended up with this error:liftIO
• Couldn't match type ‘IO’ with ‘StateT s IO’ Expected type: StateT s IO () Actual type: IO ()
The important part here is the mismatch between StateT s IO ()
and
.IO
()
Luckily, we know of a function that takes an
and returns an IO
a(m a)
:
,
enabling us to run the program and see the expected results:liftIO
> evalStateT printState "hello" "hello" > evalStateT printState 3 3
Instances
class (forall (m :: Type -> Type). Monad m => Monad (t m)) => MonadTrans (t :: (Type -> Type) -> Type -> Type) where #
The class of monad transformers.
For any monad m
, the result t m
should also be a monad,
and lift
should be a monad transformation from m
to t m
,
i.e. it should satisfy the following laws:
Since 0.6.0.0 and for GHC 8.6 and later, the requirement that t m
be a Monad
is enforced by the implication constraint
forall m.
enabled by the
Monad
m => Monad
(t m)QuantifiedConstraints
extension.
Ambiguity error with GHC 9.0 to 9.2.2
These versions of GHC have a bug (https://gitlab.haskell.org/ghc/ghc/-/issues/20582) which causes constraints like
(MonadTrans t, forall m. Monad m => Monad (t m)) => ...
to be reported as ambiguous. For transformers 0.6 and later, this can be fixed by removing the second constraint, which is implied by the first.
lift :: Monad m => m a -> t m a #
Lift a computation from the argument monad to the constructed monad.
Instances
data IdentityT (f :: k -> Type) (a :: k) #
The trivial monad transformer, which maps a monad to an equivalent monad.
Instances
newtype MaybeT (m :: Type -> Type) a #
The parameterizable maybe monad, obtained by composing an arbitrary
monad with the Maybe
monad.
Computations are actions that may produce a value or exit.
The return
function yields a computation that produces that
value, while >>=
sequences two subcomputations, exiting if either
computation does.
Instances
Reexport monadic functions
class (Alternative m, Monad m) => MonadPlus (m :: Type -> Type) where #
Monads that also support choice and failure.
Nothing
The identity of mplus
. It should also satisfy the equations
mzero >>= f = mzero v >> mzero = mzero
The default definition is
mzero = empty
An associative operation. The default definition is
mplus = (<|>
)
Instances
MonadPlus STM | Takes the first non- Since: base-4.3.0.0 |
MonadPlus P | Since: base-2.1 |
Defined in Text.ParserCombinators.ReadP | |
MonadPlus ReadP | Since: base-2.1 |
MonadPlus ReadPrec | Since: base-2.1 |
MonadPlus Seq | |
MonadPlus IO | Takes the first non-throwing Since: base-4.9.0.0 |
MonadPlus Maybe | Picks the leftmost Since: base-2.1 |
MonadPlus List | Combines lists by concatenation, starting from the empty list. Since: base-2.1 |
(ArrowApply a, ArrowPlus a) => MonadPlus (ArrowMonad a) | Since: base-4.6.0.0 |
Defined in Control.Arrow mzero :: ArrowMonad a a0 # mplus :: ArrowMonad a a0 -> ArrowMonad a a0 -> ArrowMonad a a0 # | |
MonadPlus (Proxy :: Type -> Type) | Since: base-4.9.0.0 |
MonadPlus (U1 :: Type -> Type) | Since: base-4.9.0.0 |
Monad m => MonadPlus (MaybeT m) | |
MonadPlus m => MonadPlus (Kleisli m a) | Since: base-4.14.0.0 |
MonadPlus f => MonadPlus (Ap f) | Since: base-4.12.0.0 |
MonadPlus f => MonadPlus (Alt f) | Since: base-4.8.0.0 |
MonadPlus f => MonadPlus (Rec1 f) | Since: base-4.9.0.0 |
(Monoid w, Functor m, MonadPlus m) => MonadPlus (AccumT w m) | |
(Monad m, Monoid e) => MonadPlus (ExceptT e m) | |
MonadPlus m => MonadPlus (IdentityT m) | |
MonadPlus m => MonadPlus (ReaderT r m) | |
MonadPlus m => MonadPlus (SelectT r m) | |
MonadPlus m => MonadPlus (StateT s m) | |
MonadPlus m => MonadPlus (StateT s m) | |
(Functor m, MonadPlus m) => MonadPlus (WriterT w m) | |
(Monoid w, MonadPlus m) => MonadPlus (WriterT w m) | |
(Monoid w, MonadPlus m) => MonadPlus (WriterT w m) | |
(MonadPlus f, MonadPlus g) => MonadPlus (Product f g) | Since: base-4.9.0.0 |
(MonadPlus f, MonadPlus g) => MonadPlus (f :*: g) | Since: base-4.9.0.0 |
MonadPlus f => MonadPlus (M1 i c f) | Since: base-4.9.0.0 |
(Functor m, MonadPlus m) => MonadPlus (RWST r w s m) | |
(Monoid w, MonadPlus m) => MonadPlus (RWST r w s m) | |
(Monoid w, MonadPlus m) => MonadPlus (RWST r w s m) | |
class 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 lists, Maybe
and IO
defined in the Prelude satisfy these laws.
(>>=) :: m a -> (a -> m b) -> m b infixl 1 #
Sequentially compose two actions, passing any value produced by the first as an argument to the second.
'as
' can be understood as the >>=
bsdo
expression
do a <- as bs a
(>>) :: m a -> m b -> m b infixl 1 #
Sequentially compose two actions, discarding any value produced by the first, like sequencing operators (such as the semicolon) in imperative languages.
'as
' can be understood as the >>
bsdo
expression
do as bs
Inject a value into the monadic type.
Instances
Monad Complex | Since: base-4.9.0.0 |
Monad Identity | Since: base-4.8.0.0 |
Monad First | Since: base-4.8.0.0 |
Monad Last | Since: base-4.8.0.0 |
Monad Down | Since: base-4.11.0.0 |
Monad First | Since: base-4.9.0.0 |
Monad Last | Since: base-4.9.0.0 |
Monad Max | Since: base-4.9.0.0 |
Monad Min | Since: base-4.9.0.0 |
Monad Dual | Since: base-4.8.0.0 |
Monad Product | Since: base-4.8.0.0 |
Monad Sum | Since: base-4.8.0.0 |
Monad NonEmpty | Since: base-4.9.0.0 |
Monad STM | Since: base-4.3.0.0 |
Monad Par1 | Since: base-4.9.0.0 |
Monad P | Since: base-2.1 |
Monad ReadP | Since: base-2.1 |
Monad ReadPrec | Since: base-2.1 |
Monad Put | |
Monad Seq | |
Monad Tree | |
Monad IO | Since: base-2.1 |
Monad Q | |
Monad Maybe | Since: base-2.1 |
Monad Solo | Since: base-4.15 |
Monad List | Since: base-2.1 |
Monad m => Monad (WrappedMonad m) | Since: base-4.7.0.0 |
Defined in Control.Applicative (>>=) :: WrappedMonad m a -> (a -> WrappedMonad m b) -> WrappedMonad m b # (>>) :: WrappedMonad m a -> WrappedMonad m b -> WrappedMonad m b # return :: a -> WrappedMonad m a # | |
ArrowApply a => Monad (ArrowMonad a) | Since: base-2.1 |
Defined in Control.Arrow (>>=) :: ArrowMonad a a0 -> (a0 -> ArrowMonad a b) -> ArrowMonad a b # (>>) :: ArrowMonad a a0 -> ArrowMonad a b -> ArrowMonad a b # return :: a0 -> ArrowMonad a a0 # | |
Monad (Either e) | Since: base-4.4.0.0 |
Monad (Proxy :: Type -> Type) | Since: base-4.7.0.0 |
Monad (U1 :: Type -> Type) | Since: base-4.9.0.0 |
Monad m => Monad (MaybeT m) | |
Monoid a => Monad ((,) a) | Since: base-4.9.0.0 |
Monad m => Monad (Kleisli m a) | Since: base-4.14.0.0 |
Monad f => Monad (Ap f) | Since: base-4.12.0.0 |
Monad f => Monad (Alt f) | Since: base-4.8.0.0 |
Monad f => Monad (Rec1 f) | Since: base-4.9.0.0 |
(Applicative f, Monad f) => Monad (WhenMissing f x) | Equivalent to Since: containers-0.5.9 |
Defined in Data.IntMap.Internal (>>=) :: WhenMissing f x a -> (a -> WhenMissing f x b) -> WhenMissing f x b # (>>) :: WhenMissing f x a -> WhenMissing f x b -> WhenMissing f x b # return :: a -> WhenMissing f x a # | |
(Monoid w, Functor m, Monad m) => Monad (AccumT w m) | |
Monad m => Monad (ExceptT e m) | |
Monad m => Monad (IdentityT m) | |
Monad m => Monad (ReaderT r m) | |
Monad m => Monad (SelectT r m) | |
Monad m => Monad (StateT s m) | |
Monad m => Monad (StateT s m) | |
Monad m => Monad (WriterT w m) | |
(Monoid w, Monad m) => Monad (WriterT w m) | |
(Monoid w, Monad m) => Monad (WriterT w m) | |
(Monoid a, Monoid b) => Monad ((,,) a b) | Since: base-4.14.0.0 |
(Monad f, Monad g) => Monad (Product f g) | Since: base-4.9.0.0 |
(Monad f, Monad g) => Monad (f :*: g) | Since: base-4.9.0.0 |
(Monad f, Applicative f) => Monad (WhenMatched f x y) | Equivalent to Since: containers-0.5.9 |
Defined in Data.IntMap.Internal (>>=) :: WhenMatched f x y a -> (a -> WhenMatched f x y b) -> WhenMatched f x y b # (>>) :: WhenMatched f x y a -> WhenMatched f x y b -> WhenMatched f x y b # return :: a -> WhenMatched f x y a # | |
(Applicative f, Monad f) => Monad (WhenMissing f k x) | Equivalent to Since: containers-0.5.9 |
Defined in Data.Map.Internal (>>=) :: WhenMissing f k x a -> (a -> WhenMissing f k x b) -> WhenMissing f k x b # (>>) :: WhenMissing f k x a -> WhenMissing f k x b -> WhenMissing f k x b # return :: a -> WhenMissing f k x a # | |
Monad (ContT r m) | |
(Monoid a, Monoid b, Monoid c) => Monad ((,,,) a b c) | Since: base-4.14.0.0 |
Monad ((->) r) | Since: base-2.1 |
Monad f => Monad (M1 i c f) | Since: base-4.9.0.0 |
(Monad f, Applicative f) => Monad (WhenMatched f k x y) | Equivalent to Since: containers-0.5.9 |
Defined in Data.Map.Internal (>>=) :: WhenMatched f k x y a -> (a -> WhenMatched f k x y b) -> WhenMatched f k x y b # (>>) :: WhenMatched f k x y a -> WhenMatched f k x y b -> WhenMatched f k x y b # return :: a -> WhenMatched f k x y a # | |
Monad m => Monad (RWST r w s m) | |
(Monoid w, Monad m) => Monad (RWST r w s m) | |
(Monoid w, Monad m) => Monad (RWST r w s m) | |
forever :: Applicative f => f a -> f b #
Repeat an action indefinitely.
Examples
A common use of forever
is to process input from network sockets,
Handle
s, 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 socketforkFinally
(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
and short-circuits after some number of iterations.
then MonadPlus
actually returns forever
mzero
, effectively short-circuiting its caller.
join :: 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.
'
' can be understood as the join
bssdo
expression
do bs <- bss bs
Examples
A common use of join
is to run an IO
computation returned from
an STM
transaction, since STM
transactions
can't perform IO
directly. Recall that
atomically
:: STM a -> IO a
is used to run STM
transactions atomically. So, by
specializing the types of atomically
and join
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
(=<<) :: Monad m => (a -> m b) -> m a -> m b infixr 1 #
Same as >>=
, but with the arguments interchanged.
filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a] #
This generalizes the list-based filter
function.
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 #
Left-to-right composition of Kleisli arrows.
'(bs
' can be understood as the >=>
cs) ado
expression
do b <- bs a cs b
mapAndUnzipM :: 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.
zipWithM :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m [c] #
zipWithM_ :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m () #
replicateM :: Applicative m => Int -> m a -> m [a] #
performs the action replicateM
n actact
n
times,
and then returns the list of results:
Examples
>>>
import Control.Monad.State
>>>
runState (replicateM 3 $ state $ \s -> (s, s + 1)) 1
([1,2,3],4)
replicateM_ :: Applicative m => Int -> m a -> m () #
class Monad m => MonadFail (m :: Type -> Type) where #
When a value is bound in do
-notation, the pattern on the left
hand side of <-
might not match. In this case, this class
provides a function to recover.
A Monad
without a MonadFail
instance may only be used in conjunction
with pattern that always match, such as newtypes, tuples, data types with
only a single data constructor, and irrefutable patterns (~pat
).
Instances of MonadFail
should satisfy the following law: fail s
should
be a left zero for >>=
,
fail s >>= f = fail s
If your Monad
is also MonadPlus
, a popular definition is
fail _ = mzero
fail s
should be an action that runs in the monad itself, not an
exception (except in instances of MonadIO
). In particular,
fail
should not be implemented in terms of error
.
Since: base-4.9.0.0
Instances
Reexport Maybe
The Maybe
type encapsulates an optional value. A value of type
either contains a value of type Maybe
aa
(represented as
),
or it is empty (represented as Just
aNothing
). Using Maybe
is a good way to
deal with errors or exceptional cases without resorting to drastic
measures such as error
.
The Maybe
type is also a monad. It is a simple kind of error
monad, where all errors are represented by Nothing
. A richer
error monad can be built using the Either
type.
Instances
MonadFail Maybe | Since: base-4.9.0.0 |
Defined in Control.Monad.Fail | |
Foldable Maybe | Since: base-2.1 |
Defined in Data.Foldable fold :: Monoid m => Maybe m -> m # foldMap :: Monoid m => (a -> m) -> Maybe a -> m # foldMap' :: Monoid m => (a -> m) -> Maybe a -> m # foldr :: (a -> b -> b) -> b -> Maybe a -> b # foldr' :: (a -> b -> b) -> b -> Maybe a -> b # foldl :: (b -> a -> b) -> b -> Maybe a -> b # foldl' :: (b -> a -> b) -> b -> Maybe a -> b # foldr1 :: (a -> a -> a) -> Maybe a -> a # foldl1 :: (a -> a -> a) -> Maybe a -> a # elem :: Eq a => a -> Maybe a -> Bool # maximum :: Ord a => Maybe a -> a # minimum :: Ord a => Maybe a -> a # | |
Traversable Maybe | Since: base-2.1 |
Alternative Maybe | Picks the leftmost Since: base-2.1 |
Applicative Maybe | Since: base-2.1 |
Functor Maybe | Since: base-2.1 |
Monad Maybe | Since: base-2.1 |
MonadPlus Maybe | Picks the leftmost Since: base-2.1 |
NFData1 Maybe | Since: deepseq-1.4.3.0 |
Defined in Control.DeepSeq | |
Hashable1 Maybe | |
Defined in Data.Hashable.Class | |
Generic1 Maybe | |
Lift a => Lift (Maybe a :: Type) | |
Data a => Data (Maybe a) | Since: base-4.0.0.0 |
Defined in Data.Data gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Maybe a -> c (Maybe a) # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c (Maybe a) # toConstr :: Maybe a -> Constr # dataTypeOf :: Maybe a -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c (Maybe a)) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c (Maybe a)) # gmapT :: (forall b. Data b => b -> b) -> Maybe a -> Maybe a # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Maybe a -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Maybe a -> r # gmapQ :: (forall d. Data d => d -> u) -> Maybe a -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> Maybe a -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Maybe a -> m (Maybe a) # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Maybe a -> m (Maybe a) # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Maybe a -> m (Maybe a) # | |
Semigroup a => Monoid (Maybe a) | Lift a semigroup into Since 4.11.0: constraint on inner Since: base-2.1 |
Semigroup a => Semigroup (Maybe a) | Since: base-4.9.0.0 |
Generic (Maybe a) | |
SingKind a => SingKind (Maybe a) | Since: base-4.9.0.0 |
Defined in GHC.Generics type DemoteRep (Maybe a) | |
Read a => Read (Maybe a) | Since: base-2.1 |
Show a => Show (Maybe a) | Since: base-2.1 |
NFData a => NFData (Maybe a) | |
Defined in Control.DeepSeq | |
Eq a => Eq (Maybe a) | Since: base-2.1 |
Ord a => Ord (Maybe a) | Since: base-2.1 |
Hashable a => Hashable (Maybe a) | |
Defined in Data.Hashable.Class | |
SingI ('Nothing :: Maybe a) | Since: base-4.9.0.0 |
Defined in GHC.Generics | |
SingI a2 => SingI ('Just a2 :: Maybe a1) | Since: base-4.9.0.0 |
Defined in GHC.Generics | |
type Rep1 Maybe | Since: base-4.6.0.0 |
type DemoteRep (Maybe a) | |
Defined in GHC.Generics | |
type Rep (Maybe a) | Since: base-4.6.0.0 |
Defined in GHC.Generics | |
data Sing (b :: Maybe a) | |
maybe :: b -> (a -> b) -> Maybe a -> b #
The maybe
function takes a default value, a function, and a Maybe
value. If the Maybe
value is Nothing
, the function returns the
default value. Otherwise, it applies the function to the value inside
the Just
and returns the result.
Examples
Basic usage:
>>>
maybe False odd (Just 3)
True
>>>
maybe False odd Nothing
False
Read an integer from a string using readMaybe
. If we succeed,
return twice the integer; that is, apply (*2)
to it. If instead
we fail to parse an integer, return 0
by default:
>>>
import Text.Read ( readMaybe )
>>>
maybe 0 (*2) (readMaybe "5")
10>>>
maybe 0 (*2) (readMaybe "")
0
Apply show
to a Maybe Int
. If we have Just n
, we want to show
the underlying Int
n
. But if we have Nothing
, we return the
empty string instead of (for example) "Nothing":
>>>
maybe "" show (Just 5)
"5">>>
maybe "" show Nothing
""
fromMaybe :: a -> Maybe a -> a #
The fromMaybe
function takes a default value and a Maybe
value. If the Maybe
is Nothing
, it returns the default value;
otherwise, it returns the value contained in the Maybe
.
Examples
Basic usage:
>>>
fromMaybe "" (Just "Hello, World!")
"Hello, World!"
>>>
fromMaybe "" Nothing
""
Read an integer from a string using readMaybe
. If we fail to
parse an integer, we want to return 0
by default:
>>>
import Text.Read ( readMaybe )
>>>
fromMaybe 0 (readMaybe "5")
5>>>
fromMaybe 0 (readMaybe "")
0
maybeToList :: Maybe a -> [a] #
The maybeToList
function returns an empty list when given
Nothing
or a singleton list when given Just
.
Examples
Basic usage:
>>>
maybeToList (Just 7)
[7]
>>>
maybeToList Nothing
[]
One can use maybeToList
to avoid pattern matching when combined
with a function that (safely) works on lists:
>>>
import Text.Read ( readMaybe )
>>>
sum $ maybeToList (readMaybe "3")
3>>>
sum $ maybeToList (readMaybe "")
0
listToMaybe :: [a] -> Maybe a #
The listToMaybe
function returns Nothing
on an empty list
or
where Just
aa
is the first element of the list.
Examples
Basic usage:
>>>
listToMaybe []
Nothing
>>>
listToMaybe [9]
Just 9
>>>
listToMaybe [1,2,3]
Just 1
Composing maybeToList
with listToMaybe
should be the identity
on singleton/empty lists:
>>>
maybeToList $ listToMaybe [5]
[5]>>>
maybeToList $ listToMaybe []
[]
But not on lists with more than one element:
>>>
maybeToList $ listToMaybe [1,2,3]
[1]
catMaybes :: [Maybe a] -> [a] #
The catMaybes
function takes a list of Maybe
s and returns
a list of all the Just
values.
Examples
Basic usage:
>>>
catMaybes [Just 1, Nothing, Just 3]
[1,3]
When constructing a list of Maybe
values, catMaybes
can be used
to return all of the "success" results (if the list is the result
of a map
, then mapMaybe
would be more appropriate):
>>>
import Text.Read ( readMaybe )
>>>
[readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]
[Just 1,Nothing,Just 3]>>>
catMaybes $ [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]
[1,3]
mapMaybe :: (a -> Maybe b) -> [a] -> [b] #
The mapMaybe
function is a version of map
which can throw
out elements. In particular, the functional argument returns
something of type
. If this is Maybe
bNothing
, no element
is added on to the result list. If it is
, then Just
bb
is
included in the result list.
Examples
Using
is a shortcut for mapMaybe
f x
in most cases:catMaybes
$ map
f x
>>>
import Text.Read ( readMaybe )
>>>
let readMaybeInt = readMaybe :: String -> Maybe Int
>>>
mapMaybe readMaybeInt ["1", "Foo", "3"]
[1,3]>>>
catMaybes $ map readMaybeInt ["1", "Foo", "3"]
[1,3]
If we map the Just
constructor, the entire list should be returned:
>>>
mapMaybe Just [1,2,3]
[1,2,3]
Reexport Either
The Either
type represents values with two possibilities: a value of
type
is either Either
a b
or Left
a
.Right
b
The Either
type is sometimes used to represent a value which is
either correct or an error; by convention, the Left
constructor is
used to hold an error value and the Right
constructor is used to
hold a correct value (mnemonic: "right" also means "correct").
Examples
The type
is the type of values which can be either
a Either
String
Int
String
or an Int
. The Left
constructor can be used only on
String
s, and the Right
constructor can be used only on Int
s:
>>>
let s = Left "foo" :: Either String Int
>>>
s
Left "foo">>>
let n = Right 3 :: Either String Int
>>>
n
Right 3>>>
:type s
s :: Either String Int>>>
:type n
n :: Either String Int
The fmap
from our Functor
instance will ignore Left
values, but
will apply the supplied function to values contained in a Right
:
>>>
let s = Left "foo" :: Either String Int
>>>
let n = Right 3 :: Either String Int
>>>
fmap (*2) s
Left "foo">>>
fmap (*2) n
Right 6
The Monad
instance for Either
allows us to chain together multiple
actions which may fail, and fail overall if any of the individual
steps failed. First we'll write a function that can either parse an
Int
from a Char
, or fail.
>>>
import Data.Char ( digitToInt, isDigit )
>>>
:{
let parseEither :: Char -> Either String Int parseEither c | isDigit c = Right (digitToInt c) | otherwise = Left "parse error">>>
:}
The following should work, since both '1'
and '2'
can be
parsed as Int
s.
>>>
:{
let parseMultiple :: Either String Int parseMultiple = do x <- parseEither '1' y <- parseEither '2' return (x + y)>>>
:}
>>>
parseMultiple
Right 3
But the following should fail overall, since the first operation where
we attempt to parse 'm'
as an Int
will fail:
>>>
:{
let parseMultiple :: Either String Int parseMultiple = do x <- parseEither 'm' y <- parseEither '2' return (x + y)>>>
:}
>>>
parseMultiple
Left "parse error"
Instances
Bifoldable Either | Since: base-4.10.0.0 |
Bifunctor Either | Since: base-4.8.0.0 |
Bitraversable Either | Since: base-4.10.0.0 |
Defined in Data.Bitraversable bitraverse :: Applicative f => (a -> f c) -> (b -> f d) -> Either a b -> f (Either c d) # | |
NFData2 Either | Since: deepseq-1.4.3.0 |
Defined in Control.DeepSeq | |
Hashable2 Either | |
Defined in Data.Hashable.Class | |
Generic1 (Either a :: Type -> Type) | |
(Lift a, Lift b) => Lift (Either a b :: Type) | |
IsString str => MonadFail (Either str) Source # | For convenient work with Since: 0.1.0 |
Defined in Relude.Monad.Either | |
Foldable (Either a) | Since: base-4.7.0.0 |
Defined in Data.Foldable fold :: Monoid m => Either a m -> m # foldMap :: Monoid m => (a0 -> m) -> Either a a0 -> m # foldMap' :: Monoid m => (a0 -> m) -> Either a a0 -> m # foldr :: (a0 -> b -> b) -> b -> Either a a0 -> b # foldr' :: (a0 -> b -> b) -> b -> Either a a0 -> b # foldl :: (b -> a0 -> b) -> b -> Either a a0 -> b # foldl' :: (b -> a0 -> b) -> b -> Either a a0 -> b # foldr1 :: (a0 -> a0 -> a0) -> Either a a0 -> a0 # foldl1 :: (a0 -> a0 -> a0) -> Either a a0 -> a0 # toList :: Either a a0 -> [a0] # length :: Either a a0 -> Int # elem :: Eq a0 => a0 -> Either a a0 -> Bool # maximum :: Ord a0 => Either a a0 -> a0 # minimum :: Ord a0 => Either a a0 -> a0 # | |
Traversable (Either a) | Since: base-4.7.0.0 |
Applicative (Either e) | Since: base-3.0 |
Functor (Either a) | Since: base-3.0 |
Monad (Either e) | Since: base-4.4.0.0 |
NFData a => NFData1 (Either a) | Since: deepseq-1.4.3.0 |
Defined in Control.DeepSeq | |
Hashable a => Hashable1 (Either a) | |
Defined in Data.Hashable.Class | |
(Data a, Data b) => Data (Either a b) | Since: base-4.0.0.0 |
Defined in Data.Data gfoldl :: (forall d b0. Data d => c (d -> b0) -> d -> c b0) -> (forall g. g -> c g) -> Either a b -> c (Either a b) # gunfold :: (forall b0 r. Data b0 => c (b0 -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c (Either a b) # toConstr :: Either a b -> Constr # dataTypeOf :: Either a b -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c (Either a b)) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c (Either a b)) # gmapT :: (forall b0. Data b0 => b0 -> b0) -> Either a b -> Either a b # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Either a b -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Either a b -> r # gmapQ :: (forall d. Data d => d -> u) -> Either a b -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> Either a b -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Either a b -> m (Either a b) # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Either a b -> m (Either a b) # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Either a b -> m (Either a b) # | |
Semigroup (Either a b) | Since: base-4.9.0.0 |
Generic (Either a b) | |
(Read a, Read b) => Read (Either a b) | Since: base-3.0 |
(Show a, Show b) => Show (Either a b) | Since: base-3.0 |
(NFData a, NFData b) => NFData (Either a b) | |
Defined in Control.DeepSeq | |
(Eq a, Eq b) => Eq (Either a b) | Since: base-2.1 |
(Ord a, Ord b) => Ord (Either a b) | Since: base-2.1 |
(Hashable a, Hashable b) => Hashable (Either a b) | |
Defined in Data.Hashable.Class | |
type Rep1 (Either a :: Type -> Type) | Since: base-4.6.0.0 |
Defined in GHC.Generics type Rep1 (Either a :: Type -> Type) = D1 ('MetaData "Either" "Data.Either" "base" 'False) (C1 ('MetaCons "Left" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 a)) :+: C1 ('MetaCons "Right" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) Par1)) | |
type Rep (Either a b) | Since: base-4.6.0.0 |
Defined in GHC.Generics type Rep (Either a b) = D1 ('MetaData "Either" "Data.Either" "base" 'False) (C1 ('MetaCons "Left" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 a)) :+: C1 ('MetaCons "Right" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 b))) |
either :: (a -> c) -> (b -> c) -> Either a b -> c #
Case analysis for the Either
type.
If the value is
, apply the first function to Left
aa
;
if it is
, apply the second function to Right
bb
.
Examples
We create two values of type
, one using the
Either
String
Int
Left
constructor and another using the Right
constructor. Then
we apply "either" the length
function (if we have a String
)
or the "times-two" function (if we have an Int
):
>>>
let s = Left "foo" :: Either String Int
>>>
let n = Right 3 :: Either String Int
>>>
either length (*2) s
3>>>
either length (*2) n
6
partitionEithers :: [Either a b] -> ([a], [b]) #
Partitions a list of Either
into two lists.
All the Left
elements are extracted, in order, to the first
component of the output. Similarly the Right
elements are extracted
to the second component of the output.
Examples
Basic usage:
>>>
let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
>>>
partitionEithers list
(["foo","bar","baz"],[3,7])
The pair returned by
should be the same
pair as partitionEithers
x(
:lefts
x, rights
x)
>>>
let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
>>>
partitionEithers list == (lefts list, rights list)
True
isLeft :: Either a b -> Bool #
Return True
if the given value is a Left
-value, False
otherwise.
Examples
Basic usage:
>>>
isLeft (Left "foo")
True>>>
isLeft (Right 3)
False
Assuming a Left
value signifies some sort of error, we can use
isLeft
to write a very simple error-reporting function that does
absolutely nothing in the case of success, and outputs "ERROR" if
any error occurred.
This example shows how isLeft
might be used to avoid pattern
matching when one does not care about the value contained in the
constructor:
>>>
import Control.Monad ( when )
>>>
let report e = when (isLeft e) $ putStrLn "ERROR"
>>>
report (Right 1)
>>>
report (Left "parse error")
ERROR
Since: base-4.7.0.0
isRight :: Either a b -> Bool #
Return True
if the given value is a Right
-value, False
otherwise.
Examples
Basic usage:
>>>
isRight (Left "foo")
False>>>
isRight (Right 3)
True
Assuming a Left
value signifies some sort of error, we can use
isRight
to write a very simple reporting function that only
outputs "SUCCESS" when a computation has succeeded.
This example shows how isRight
might be used to avoid pattern
matching when one does not care about the value contained in the
constructor:
>>>
import Control.Monad ( when )
>>>
let report e = when (isRight e) $ putStrLn "SUCCESS"
>>>
report (Left "parse error")
>>>
report (Right 1)
SUCCESS
Since: base-4.7.0.0