State Transformer

Albert Lai
11 Jan 2002 16:40:57 -0500

> > testfunc = do
> >            r <- newSTRef ('x',0)
> >            foo r
> >            bar r
> >            (c,n) <- readSTRef r
> >            return n

Jorge Adriano <> writes:

> Yeap, I could do it like this myself :)
> The whole problem is with passing the 'r' as a parameter, which is precisly 
> what I'm trying to avoid.

I agree with you.  My work-around is then to define foo and bar locally
to testfunc, in the scope of r:

testfunc = do
           r <- newSTRef ('x',0)
           let foo = do
                     (c,n) <- readSTRef r
                     writeSTRef r ('a', n+1)
               bar = do
                     (c,n) <- readSTRef r
                     writeSTRef r (c,n+2)
           (c,n) <- readSTRef r
           return n

But if this looks like unsatisfactory (it does to me, too), perhaps
you have to go back to DIY monads.

DIY monads are good when: you fix the state variables, you don't want
to mention them in subprogram parameters.

The ST monad is good when: you create more state variables on the fly,
you use mutable arrays, you don't want to write your own monad and
put/get commands.