[Haskell-cafe] stack overflow when using ST monad

Chris Kuklewicz haskell at list.mightyreason.com
Thu Aug 24 07:46:34 EDT 2006


The write*Ref functions, like many "write into data structure" have the common 
problem of being much lazier than you want.  The nextState calls form a lazy 
thunk.  In fact it tries form 10^6 nested thunks to call nextState.  So you have 
to use something like seq to reduce the laziness:

> 
> step :: Tag s -> ST s (Maybe Integer)
> step t = do
>         c <- readSTRef (count t)
>         s <- readSTRef (state t)
>         writeSTRef (count t) (c - 1)
>         let state'=nextState s
>         state' `seq` writeSTRef (state t) state'
>         if (c <= 0) then return Nothing else return (Just c)



More information about the Haskell-Cafe mailing list