[Haskell-beginners] Control.Monad.State: State CTOR unneeded to
create a State?
aslatter at gmail.com
Thu Oct 30 22:20:50 EDT 2008
On Thu, Oct 30, 2008 at 10:07 PM, Larry Evans <cppljevans at suddenlink.net> wrote:
> suggests, with the content:
> State runState :: (s -> (a, s))
> that State has a labeled constructor:
> yet the Examples section:
> shows, AFAICT, no call to the State CTOR:
> tick :: State Int Int
> tick = do n <- get
> put (n+1)
> return n
> I assume the n must be an Int (since it's in n+1), but what are
> get and put. There is a get and put described here:
> however, I don't see how they are relevant since they are defined for
> an already existing MonadState, and AFAICT, tick hasn't been defined
> yet since it's on the lhs of the =.
> Please, what am I missing?
Hi Larry. Event thought 'get' and 'put' are defined in MonadState,
the concrete implementation of them for "State s a" uses the 'State'
constructor. They probably look something like so:
get = State (\s -> (s,s))
put newS = State (\oldS ->( (), newS ))
Also, the definitions of the 'Monad' class functions also need to use
the 'State' constructor, for example return should look something
return x = State (\s -> (x, s))
So when you use expressions in a 'do' block, or 'get' or 'put' then
under the hood you're using the 'State' constructor.
Then at the top-level you use 'runState :: State s a -> s -> (a,s)' to
strip the constructor away.
As long as you aren't writing anything that needs to dig to much into
the workings of 'State', you shouldn't have to worry too much about
I hope I haven't made things more confused ^_^
More information about the Beginners