[Haskell-beginners] how does the State monad actually work?

Aleksandar Dimitrov aleks.dimitrov at googlemail.com
Thu May 26 11:23:45 CEST 2011


On Tue, May 24, 2011 at 9:50 AM, Benjamin Edwards <edwards.benj at gmail.com>wrote:

> I highly recommend reading some of the tutorials that show how to derive
> the state monad. The type of state is really a function that takes a
> parameter and returns a state tupled with a value. Yet another haskell
> tutorial has quite a good chapter on this.
>
Personally, I think one should have a look at the "Monads" chapter in RWH,
and maybe also LYAH. Here are the respective links:
http://book.realworldhaskell.org/read/monads.html#monads.state and
http://learnyouahaskell.com/for-a-few-monads-more#state (also take a look at
the preceding chapter in LYAH, since it introduces Monads more generally.)

>  I get "blah" as expected. When I switch to execState I get the value 1.
> This is what confuses me. Where is the State coming from if it is not passed
> into foo? What are get and put operating on?
>
> get does not need a parameter. It executes in the state monad, and get is
defined to retrieve the computation's enclosing state. Put *does* take a
parameter, and that is the new state for the state monad. Mind you, the
state is not *implicit* -- it is, in fact, made explicit in the type
signature; but it looks as if it were implicit in the definition of your
function. In any case, you do not need to supply the value of the state to
either get or put as a parameter, because both are designed around chaining
stateful computations together without passing around the state in the
function's arguments!

execState and runState just do different things. Look at the type signatures
using hoogle:

execState :: State s a -> s -> s
runState :: State s a -> s -> (a, s)
evalState :: State s a -> s -> a

State itself is defined as a tuple of state and result. runState is the
function you use to retrieve both. evalState and execState just produce
special cases of runState (i.e. they retrieve either one or the other member
of the tuple.)

HTH,
Aleks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20110526/64bf36be/attachment.htm>


More information about the Beginners mailing list