Haskell-Cafe digest, Vol 1 #293 - 4 msgs

Jay Cox sqrtofone@yahoo.com
Fri, 11 Jan 2002 13:03:57 -0600 (CST)

> Message: 4
> From: Jorge Adriano <jadrian@mat.uc.pt>
> To: haskell-cafe@haskell.org, glasgow-haskell-users@haskell.org
> Subject: State Transformer
> Date: Mon, 7 Jan 2002 15:41:57 +0000


> Till then I had just read what I needed to be able to use the IO Monad.
> Seems to me like having a State Transformer monad its the best way to do it.
> Now I've read a great deal of Richard Birds Book chap 10 (Monads), as well as
> the "Monads for the Haskell Working Programmer"[1] by Theodore Norvell.
> I was going to try to make my own simple examples using a ST.
> A State Monad seemed something like would most probably be in some Standard
> Library, or at least in some GHC library.
> And it was (section 4.31.ST in the hslibs documentation)
> I wanted to use this ST, but then I noticed it was different from the one
> described in tutorial[1].
> I was expecting the ST Monad ghc module to provide an apply function,
> analogue to the
> > applyST :: StateTrans s a -> s -> (s, a)
> > applyST (ST p) s = p s

I believe you want runST.  its type is not

> in the tutorial.
> I also expected to have general functions to access and change State. I can't
> implement them myself since the ST constructor is (obviously) not exported.
> But this ST module seems to work in a completely diferent way.
> >From what I can tell it is not suposed to be applyed to an initial state,
> instead it starts with an 'empty' state...
> State is controled with Referencies (mutable variables).

yes, you can initialize any number of mutable variables from within
the state monad.

> Ok, now my problem, how do I use this?
> ----------------------------------------
> stupidFunc
>     runST (
>      do {
>       initstate <- newSTRef ('x',0)
>       -- and now what?
> 	})
> -----------------------------------------
import ST

main = print (runST (do { x <-newSTRef 3;add1 x; y<-newSTRef "Elvis";
saysomething y; a<-readSTRef x; b<-readSTRef y; return (a,b)}))

add1 a = do
           l <-readSTRef a
           writeSTRef a (l+1)

saysomething y = modifySTRef y leftthebuilding

leftthebuilding x = x ++ " has left the building."

compile the above code with -package lang

perhaps that'll give you some idea how to deal with STRefs and all.

Jay Cox