[Haskell-cafe] Can we come out of a monad?
Anton van Straaten
anton at appsolutions.com
Fri Jul 30 03:49:10 EDT 2010
C K Kashyap wrote:
> In the code here -
> If I look at the type of modifiedImage, its simply ByteString - but
> isn't it actually getting into and back out of the state monad? I am of
> the understanding that once you into a monad, you cant get out of it? Is
> this breaking the "monad" scheme?
modifiedImage uses the execState function, which has the following type:
execState :: State s a -> s -> s
In other words, it applies a State monad value to a state, and returns a
new state. Its entire purpose is to "run" the monad and obtain the
A monadic value of type "State s a" is a kind of delayed computation
that doesn't do anything until you apply it to a state, using a function
like execState or evalState. Once you do that, the computation runs,
the monad is "evaluated away", and a result is returned.
The issue about not being able to escape that (I think) you're referring
to applies to the functions "within" that computation. A State monad
computation typically consists of a chain of monadic functions of type
(a -> State s b) composed using bind (>>=). A function in that composed
chain has to return a monadic value, which constrains the ability of
such a function to escape from the monad.
Within a monadic function, you may deal directly with states and
non-monadic values, and you may run functions like evalState or
execState which eliminate monads, but the function still has to return a
monadic value in the end, e.g. using "return" to lift an ordinary value
into the monad.
More information about the Haskell-Cafe