
yet I need to add a $! to the recursive call of isum to get a truly
iterative ???
Wait a minute Patai. How would you do that? I'm only beginner I thought I
can only add strict "!" to data parameters. But to make isum function strict
would be helpful.
Thanks
On Mon, Nov 3, 2008 at 7:36 PM, Don Stewart
patai_gergely:
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?
I think its sensible not to rely on an analysis to infer the correct reduction strategy for your code. Make the strictness explict, and your code will be more portable and more robust.
Also, write in some type annotations. Particularly for atomic types like Int, these give the strictness analyser yet more information to work with.
-- Don _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe