I have an algorithm for calculating the nth Fibonacci number, in Python it’s expressed as:
def fib(n):
if n == 0:
return 1
if n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
and in Haskell:
fib :: Integer -> Integer
fib 0 = 1
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
I would have expected Haskell to evaluate faster or around the same time, but if using a number above say n=40, python code evaluates much (~x3) faster. I’m using GHCi and Ipython but I didn’t think that should make a difference.
You said that you ran the Haskell code in GHCI, which means that you ran it without optimizations. That means that no strictness analysis was done, so the whole thing was evaluated lazily, creating a lot of unnecessary thunks. That would explain why it was slower.
Also as delnan pointed out in a comment, ghci is much slower than compiling the code with ghc and then running it – even without optimizations. When I test your code on my PC, running after compiling without optimizations takes twice as long as with optimizations, but still less time than running the Python code. Running in ghci takes a whole lot longer than that.