Fibonacci in Haskell freezes pc?

Viewed 91

I'm a beginner in Haskell, and I was trying to write the fibonacci function, but every time I run it my pc freezes. I have no idea why. This is my code:

fib n = if n<=2 then 1 else (fib n-1)+(fib n-2)

I don't know if it is of any help but I'm using GHC in Ubuntu 20.04

2 Answers

I think, you meant to write

fib n = if n<=2 then 1 else fib (n-1) + fib (n-2)

fib n-1 will be interpreted as (fib n) - 1. That is why you have an infinite recursion.

fib n-1 is interpreted as (fib n) - 1, so you get stuck in an infinite loop, since you call fib n, when evaluating fib n. It will eventually exhaust memory since the expression tree will each time be larger.

You can fix this with:

fib n = if n <= 2 then 1 else (fib (n-1)) + (fib (n-2))

but this will still take exponential time. You can evaluate this in linear time with:

fib :: (Eq a, Integral a, Integral b) => a -> b
fib n = go n 0 1
    where go 0 a _ = a
          go n a b = go (n-1) b (a+b)
Related