I'm trying so hard to wrap my head around the State Monad, and I do not understand the following:
Given the implementation of return
and (>>=)
, when you say State $ \s ->....
, where does s
come from? I mean, when you start performing >>= ... >>=
, doesn't it mean that somewhere in your beginning of the chain you somehow have to provide for that initial parameter?
newtype State s a=State { runState::s->(a,s) }
instance Monad (State s) where
return a=State $ \s->(a,s)
(>>=) m g=State $ \s -> let (a,s')= runState m s in
runState (g a) s'
In (>>=)
you say State $ \s -> runState m s
, and I do not get when is that initial (\s -> ...) argument
(with a REAL argument
) called?
Can someone explain, please?
Later Edit:
Can someone show me how would the initial
state be set, let's say if it needs to get a value using getLine
?
main::IO()
main=do
argument<-getLine
--how do i set initial state with argument?
m >> f1 >> f2 >> f3
State
. AState
is in fact not the sate, but a change of state. We thus create a new change of state that first passess
through the first one, and the result(a, s')
contains the modified states'
that is then passed to the next one.State s a
value as a "state transformer", a machine which can modify the state, when fed with one, and produce a value of typea
in the process. The concrete, real, initial state is passed when one finally decides to run the monadic computation usingrunState myStateValue myInitialState
. This is a typical workflow with monads: you use a lot of>>=/return
to build a value of typeM a
, and at the very last step you userunM
to turn thatM a
into some usable type, breaking the monadic abstraction.let x = runState st argument
inside your IO do block, orrunState (do { x <- get ; return (x+1) }) 0
. but that is a new question.