A type f is a Functor if it provides a function fmap which, given any types a and b
lets you apply any function from (a -> b) to turn an f a into an f b, preserving the
structure of f. Furthermore f needs to adhere to the following:
Note, that the second law follows from the free theorem of the type fmap and
the first law, so you need only check that the former condition holds.
See these articles by School of Haskell or
David Luposchainsky
for an explanation.
fmap is used to apply a function of type (a -> b) to a value of type f a,
where f is a functor, to produce a value of type f b.
Note that for any type constructor with more than one parameter (e.g., Either),
only the last type parameter can be modified with fmap (e.g., b in `Either a b`).
Some type constructors with two parameters or more have a Data.Bifunctor instance that allows
both the last and the penultimate parameters to be mapped over.
Examples
Convert from a Maybe Int to a Maybe String
using show:
Example2 expressions
>>> fmap show NothingNothing>>> fmap show (Just 3)Just "3"
Convert from an Either Int Int to an
Either Int String using show:
Example2 expressions
>>> fmap show (Left 17)Left 17>>> fmap show (Right 17)Right "17"
It may seem surprising that the function is only applied to the last element of the tuple
compared to the list example above which applies it to every element in the list.
To understand, remember that tuples are type constructors with multiple type parameters:
a tuple of 3 elements (a,b,c) can also be written (,,) a b c and its Functor instance
is defined for Functor ((,,) a b) (i.e., only the third parameter is free to be mapped over
with fmap).
It explains why fmap can be used with tuples containing values of different types as in the
following example:
Replace all locations in the input with the same value.
The default definition is fmap . const, but this may be
overridden with a more efficient version.
Examples
Perform a computation with Maybe and replace the result with a
constant value if it is Just:
Example2 expressions
>>> 'a' <$ Just 2Just 'a'>>> 'a' <$ NothingNothing
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.
A common use of forever is to process input from network sockets,
System.IO.Handles, and channels
(e.g. Control.Concurrent.MVar.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:
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.
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.
Map each element of a structure to a monadic action, evaluate
these actions from left to right, and ignore the results. For a
version that doesn't ignore the results see
Data.Traversable.mapM.
mapM_ is just like traverse_, but specialised to monadic actions.
Evaluate each monadic action in the structure from left to right,
and ignore the results. For a version that doesn't ignore the
results see Data.Traversable.sequence.
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 see Data.Foldable.mapM_.
Examples
mapM is literally a traverse with a type signature restricted
to Monad. Its implementation may be more efficient due to additional
power of Monad.
Evaluate each monadic action in the structure from left to
right, and collect the results. For a version that ignores the
results see Data.Foldable.sequence_.
Examples
Basic usage:
The first two examples are instances where the input and
and output of sequence are isomorphic.
Example1 expression
>>> sequence $ Right [1,2,3,4][Right 1,Right 2,Right 3,Right 4]
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.
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.
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.
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.
This function should not be different from its default implementation
as pure. The justification for the existence of this function is
merely historic.
Instances65Monad, …
MonadComplexDefined in base-4.20.2.0 · Data.Complex
MonadFirstDefined in base-4.20.2.0 · Data.Semigroup
MonadLastDefined in base-4.20.2.0 · Data.Semigroup
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 Monaddo-notation:
safeDiv :: Int -> Int -> Maybe Int
safeDiv x y = do
guard (y /= 0)
return (x `div` y)
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.
Instances25MonadFail, …
MonadFailMaybeDefined in ghc-internal-9.1003.0 · GHC.Internal.Control.Monad.Fail
MonadFailPDefined in ghc-internal-9.1003.0 · GHC.Internal.Text.ParserCombinators.ReadP
MonadFailReadPDefined in ghc-internal-9.1003.0 · GHC.Internal.Text.ParserCombinators.ReadP
MonadFailReadPrecDefined in ghc-internal-9.1003.0 · GHC.Internal.Text.ParserCombinators.ReadPrec
MonadFailIODefined in ghc-internal-9.1003.0 · GHC.Internal.Control.Monad.Fail
MonadFailQDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
MonadFail []Defined in ghc-internal-9.1003.0 · GHC.Internal.Control.Monad.Fail
Monadm => MonadFail (CatchTm)Defined in exceptions-0.10.9 · Control.Monad.Catch.Pure
Monadm => MonadFail (MaybeTm)Defined in transformers-0.6.1.1 · Control.Monad.Trans.Maybe
MonadFailf => MonadFail (Apf)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Monoid