On Tue, May 24, 2011 at 9:50 AM, Benjamin Edwards <edwards.benj@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.
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