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

Benjamin Edwards edwards.benj at gmail.com
Tue May 24 09:50:19 CEST 2011


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.

On 24 May 2011 08:40, "Sean Perry" <shaleh at speakeasy.net> wrote:

I am trying to understand how the State ends up in the function.

foo :: State Int String
foo = do
   tmp <- get
   put (tmp + 1)
   return "blah"

when invoked as

print $ evalState foo 0

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?

Desugared foo becomes:
(get >>= \tmp -> put (tmp + 1)) >> return "blah"

Which shows my confusion perfectly. Neither get nor put take a parameter.
Why is that? How does return know to include them in the new State value?
Especially considering the use of ">>".

Obviously I can use State instances following examples like this but I can
not reason with them since there is still a feeling of magic to them.

Thanks.


_______________________________________________
Beginners mailing list
Beginners at haskell.org
http://www.haskell.org/mailman/listinfo/beginners
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20110524/230abdb8/attachment.htm>


More information about the Beginners mailing list