Hi, I have sent this message to the hugs-users list but I don't know if
it really works so I ask it again in this list.

I need to work with ST and STArray to implement in Haskell an algorithm 
wich was written in C. 

I am using HUGS 1.4 beta (970719) in WIndows 95

The next problem is very simplified but I don't know how to solve it in
an efficient way:

Suppose you want to implement the sum of the first n integers using a 
MutVar as a temporal store. 

The imperative algorithm could be: "for i=1 to n do x:=x+i; "

I know that you could type "sum [1..n]" but suppose you want to mirror the
imperative style and use the next code (I know it looks imperative :)

-------------------------------------------------
test::Int->Int
test n = runST
          ( do
             x <- newVar 0
             s <- mkSums n x
             v <- readVar x
             return v
          )

mkSums::Int -> MutVar s Int -> ST s ()
mkSums n x = sequence [mkSum x i | i<- [1..n]]

mkSum::MutVar s Int->Int->ST s ()
mkSum x i = do
              val <- readVar x
              writeVar x (val + i)
-------------------------------------------------

Well, the problem is that it gets a "Control stack overflow" when n is 
large.

I think the problem is with "mkSums" but I don't know if there is
a different way to specify that I want to repeat a process n times 
in Haskell without creating the list [1..n] and folding it.
any suggestions?


BTW, The algorithms use random numbers and I thought it 
would be a good idea to use a state transformer monad. 

I have implemented the state transformer monad with 2 approaches:
- state = an infinite list (transition = drop the head)
- state = MutVar (transition = update the contents of MutVar, similar to the previous 
code)
Which one do you think is better?

Thanks, Jose Emilio Labra Gayo
Univ. of Oviedo
Dept. of Computer Science
email: [EMAIL PROTECTED]
http://www.uniovi.es/~oviedo3/Enlaces/Personal/Labra

Reply via email to