State Transformer

Theodore Norvell
Fri, 11 Jan 2002 23:33:39 -0800 (PST)

> DIY? what does that means?

Do It Yourself. I.e. as in my tutorial.

> What if you want both and keep nice clean(*) programming style... :-)

You can compose monads.  I've done something like the following in
the past (only with IO):
    data StateTrans s a = StateTrans (s -> ST (s,a))
Here s is the global state.  A function that changes
the global state
   f :: s -> s
can be lifted into the monad by
    listGlobalMutator :: (s -> s) -> StateTrans s a
    liftGlobalMutator f = StateTrans (\s -> return (f s, ()))
    liftGlobalAccessor :: (s -> a) -> StateTrans s a
    liftGlobalAccessor g = StateTrans (\s -> return (s, g s))
    liftST :: ST a -> StateTrans s a
    liftST st = StateTrans (\s -> do { a<- st ; return (s, a)})

This gives you a fixed global state (which could be a tuple
of global variables) and as many dynamic variables (accessed via
references) as you want.

Probably I should have used a strict pair type above instead
of (,).

Theo Norvell