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

Sean Perry shaleh at speakeasy.net
Tue May 24 09:41:25 CEST 2011


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.




More information about the Beginners mailing list