simple program crash (GHC 5.02, Hugs)

Max A.K. max630@mail.ru
Sat, 22 Dec 2001 09:55:16 +0600


On Fri, Dec 21, 2001 at 04:22:42PM -0600, Oleg Galbert wrote:
> test n cosx
>         | n==0 = cosx
>         | otherwise = test (n-1) (cosx+cos(cosx))

Functions by default are lazy, i.e. they does not compute
the number, but make a note to do it later. In the example
you presented, the value of cosx is not needed until the call
for "test (n-1) (cosx+cos(cosx))". So, as a result of
"test 10000000 0.0" you get a (...+cos(0.0+cos(0.0)))...).
That's not surprising it crashes the program.

> test1 n cosx
>	| n==0 = cosx
>	| otherwise = cosx `seq` test1 (n-1) (cosx+cos(cosx))

Here, you make sure that cosx is counted up to a number.
This function works OK.

read http://haskell.org/ghc/docs/latest/set/faster.html

> main = print ( test  10000000 0.0 )  

> Oleg Galbert

Max.