
On Mon, 2008-11-03 at 13:31 +0100, Patai Gergely wrote:
Hi everyone,
I was experimenting with simple accumulator functions, and found that an apparently tail recursive function can easily fill the stack. Playing around with ghc and jhc gave consistently unpleasant results. Look at this program:
%%%%%%%%%%%
-- ghc: no, ghc -O3: yes, jhc: no isum 0 s = s isum n s = isum (n-1) (s+n)
-- ghc: no, ghc -O3: no, jhc: yes (because gcc -O3 is clever) rsum 0 = 0 rsum n = n + rsum (n-1)
main = case isum 10000000 0 {- rsum 10000000 -} of 0 -> print 0 x -> print x
%%%%%%%%%%%
I would expect the analysis to find out that the result of the function is needed in every case (since we are matching a pattern to it), yet I need to add a $! to the recursive call of isum to get a truly iterative function. It's interesting how ghc and jhc seem to diverge, one favouring the "iterative" version, the other the "recursive" one (although it only works because gcc figures out that the function can be expressed in an iterative way).
Of course this is a real problem when I'm trying to write an actual program, since it means I can be bitten by the laziness bug any time... Is there any solution besides adding strictness annotations? Can I expect the compiler to handle this situation better in the foreseeable future?
Don't write code that relies on strictness analysis for correctness.