Strict<->Lazy?
Richard A. O'Keefe
ok@atlas.otago.ac.nz
Fri, 2 Jul 1999 08:25:28 +1200 (NZST)
fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib n = fib (n-1)+fib(n-2)
Er, fib 0 is ONE, not ZERO.
This took my computer about 21.5 seconds to calaculate the 40-th
number.
I haven't cared to try fib(40) because I'm using an 84MHz machine
and fib(35) is already interesting. Interestingly, this definition
took 6.8 seconds for fib(35), whereas
fib n = if (n < 2) 1 (fib (n-1) + fib (n-2))
took 5.7 seconds.
But when rewriting the algorithm to
fib2 :: Int -> Int
fib2 n = fibList !! n
where
fibList = [0,1:[i+j \\ i <- fibList & j <- tl fibList]]
the computing time became negligible.
Yes, but that is a DIFFERENT ALGORITHM (also computing non-Fibs thanks
to the 0 that should have been 1); the same algorithm can be used in C
to speed the C version up too. For the record, fib(40) took so long
in C that I didn't bother to wait for it.