[Haskell-beginners] Control.Monad.State: State CTOR unneeded to create a State?

Antoine Latter 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:
> Page:
>
>  http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-State.html#2
>
> suggests, with the content:
>
>  Constructors
>   State         runState :: (s -> (a, s))
> that State has a labeled constructor:
>
>  http://www.haskell.org/onlinereport/exps.html#sect3.15.2
>
> yet the Examples section:
>
>  http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-State.html#4
>
> 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
> the
> get and put.  There is a get and put described here:
>
>  http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-State.html#1
>
> 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
like:

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
it.

I hope I haven't made things more confused ^_^

-Antoine


More information about the Beginners mailing list