I made two different Fibonacci functions, the first one worked perfectly. Then I tried to simplify it in an intuitive way. I thought it would work but for some reason it says ERROR: Out of local stack every time I test it.
Working version:
fibonacci(0,0).
fibonacci(1,1).
fibonacci(N,F) :- N1 is N-1, N2 is N-2, fibonacci(N1,F1), fibonacci(N2,F2), F is F1+F2.
Not working version:
fibonacci(0,0).
fibonacci(1,1).
fibonacci(N,F) :- fibonacci(N-1,F1), fibonacci(N-2,F2), F is F1+F2.
Could someone explain me what is the problem with the second one? Thanks.
Your problem is that in your second one you are recursively calling fibonacci/2 with the term
N-1instead of an integer whose value is N-1.So, for example if you where calling
fibonacci(3, F)it would enter in the third clause and callfibonacci(3-1, F1)instead offibonacci(2, F1). It would then enter again in the third clause and callfibonacci(3-1-1, F1)and so on.Note that Prolog uses special operator
isto perform arithmetic operations.The first example is right.