[Haskell-cafe] Re: How do I get a long iteration to run in constant space

oleg at pobox.com oleg at pobox.com
Tue Oct 5 03:44:40 EDT 2004

I added two lines to your code:

iterate2 f x n | seq f $ seq x $ seq n $ False = undefined
iterate2 f x n = --- as before

rk4Next f h (x, y) | seq f $ seq h $ seq x $ seq y $ False = undefined
rk4Next f h (x, y) = -- as before

I also increased ten times the number of steps for the last iteration,
to make the example more illustrative.
   putStr (show (rk4 stiff 0 1 (exp (-1)) 1000000))

The rest of the code is unchanged. The program now runs on GHCi

*Foo> main

on on hugs


with the default stack size for both interpreters. It seems the code
does run in constant space now.

The added lines are meant to turn the relevant functions from lazy to
strict. When you see something like '(n-1)' and 'y + a1/6', it is a
red flag. These are exactly the kinds of expressions that lead to
memory exhaustion. Perhaps it is because the size of an unevaluated
thunk for (n-1) is so much bigger than the size of the evaluated
thunk. It seems that arithmetic expressions are the best candidates
for some opportunistic evaluation...

More information about the Haskell-Cafe mailing list