[Haskell-cafe] Very simple parser

Arie Peterson ariep at xs4all.nl
Mon Jul 2 19:51:59 EDT 2007


Gregory Propf wrote:

| [...] For example, am I to assume that I need to
| create my own instance of State and then define get and put for it?

No, there is a 'State s' monad provided (for arbitrary state type 's'),
which implements the 'get' and 'put' methods. In other words, 'State s' is
an instance of the 'MonadState s' class. This terminology can be really
confusing at first.

For now, you may forget about the MonadState class. Simply use 'get' &
friends and everything will work fine.

To get you going, start with the example from the documentation, modified
slightly:

> tick :: State Int String
> tick = do
>   n <- get
>   put (n+1)
>   return (show n)

If you want to actually run 'tick', use the 'runState' function:

> runTick :: Int -> (String,Int)
> runTick = runState tick

The argument of 'runTick' is used as initial state.
The returned String is the return value, the Int is the final state.

Now, put this code in a module and load it in an interpreter (ghci,
hugs,...). Unleash 'runTick' on an integer number of your choice, and
convince yourself that the result is what you would expect from the
definition of 'tick'.

Next, try to make some variants of 'tick': replace the return value by
something else, or use a list [Int] as state, instead of a single number.


Shout if you need more or other help.


Kind regards,

Arie




More information about the Haskell-Cafe mailing list