I am just beginner in Haskell. And I writing a code to display the N numbers in the Fibonacci sequence. Here is my code in Haskell,
fib_seq 1 = 1:[]
fib_seq 2 =
Guess what happens if "fib_seq (n-1)" is evaluated twice on each recursion. And then try this:
fib_seq 1 = 1:[]
fib_seq 2 = 1:1:[]
fib_seq n = sum(take 2 f):f
where f = fib_seq (n-1)
The following program, compiled with ghc -O2 test.hs
, is +/-2% the speed of the C code you posted, compiled with gcc -O2 test.c
.
fib_seq :: Int -> Int
fib_seq 1 = 1
fib_seq 2 = 1
fib_seq n = fib_seq (n-1) + fib_seq (n-2)
main = mapM_ (print . fib_seq) [40,39..1]
Some comments:
Integer
instead of Int
for largenum arithmetic, and having a class-polymorphic type instead of a monomorphic one adding overhead on every function call.Of course using one of the many well-known better algorithms for fibonacci is going to trump all this nonsense.