[Haskell-cafe] foldl to foldl' , ok ; but with foldM ?

minh thu noteed at gmail.com
Sun May 14 07:38:33 EDT 2006


Hi, I know the question is raised often but i cannot find the answer.

In a previous mail, I was said to use foldl' instead of foldl and it
worked really well :

   acc1 values = foldl1' (+) values

How is foldl' defined ?


I have two other related questions :

What if I want to write something like this :

   foldl' f emptyArray values

where f accumulates a value into an array.
What's the best representation for an array here ?

Also, given the fact that I though to represent my array with a c-like
Ptr Word8 array,
i tried this code, where the accumulator is referenced by an IORef :

acc2 ints = do
     accRef <- newIORef 0
     foldM add accRef ints
     acc <- readIORef accRef
     putStrLn $ show acc
     return acc
 where add accRef i = do
         modifyIORef accRef (+ i)
         return accRef

but it's far worse than the code with foldl'.
I guess someone will tell me to try to strictify something... but I
don't know what and how.
I think trying to strictify the accRef is worthless : it's the
referenced acc that needs to be evaluated. Is-it correct ?


Thanks !!
VO Minh Thu


More information about the Haskell-Cafe mailing list