[Haskell-beginners] Control.Monad.State: State CTOR unneeded to
create a State?
Luca Padovani
padovani at sti.uniurb.it
Sat Nov 1 11:48:38 EDT 2008
Hi Larry,
I approached Haskell very recently and I see in your posts many doubts
that I experienced myself, so perhaps I can be of some help by
providing you with the intuition that guided me, rather than with an
in depth explanation of how monadic state works.
On Sat, Nov 1, 2008 at 5:23 PM, Larry Evans <cppljevans at suddenlink.net> wrote:
>> get = State (\s -> (s,s))
>> put newS = State (\oldS ->( (), newS ))
>
> That still leaves me confused about:
>
> put (n+1)
>
> AFAICT, with the preceding |n <- get|, this means:
>
> put (get+1)
pretty much as with IO, you shouldn't think of get as of a function
(or value) representing the value of the state, nor should you think
of put as of a function that modifies the state. You should think of
get and put (n + 1) as of *actions* that, *when performed*, will read
and write the state. In particular
put (n + 1)
is NOT equivalent to
put (get + 1)
because "get" here is not the state (of value Int), but it's an action
that lets you access the state and
n <- get
is the way you have to say that you want to perform the get action and
bind the value in the state to the name n.
The thing that I found really weird in the beginning was that with
State the state is never mentioned anywhere! But there is where the
intuition "action that reads/writes the state" comes into the game.
--luca
More information about the Beginners
mailing list