Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fibonacci recursive functor

I am a beginner to Prolog and i want help with this this functor calculate the fibonacci of a number ... first time it adds Y = 0 and Z = 1 then it calls itself wtih Y = Z and Z = Y + Z and each time it increments the value of the counter C until the counter equals to X..... the problem is the result always is equal to 1 because prolog never executes second clause even if X not equal to M but i don't know why .....

X: the fibonacci to be calculated Y : the first number in fibonacci series Z : second number in fibonacci series C : counter with 0 as intial value
T : Y + Z

predicates
fib_tail(integer,integer, integer,integer, real)
clauses
fib_tail(X,Y , Z,M, T):- X=M,T = Y + Z,!.
fib_tail(X,Y ,Z, C , T):-
  T = Y + Z,
  NY = Z,
  NZ = Y + Z,
  NC = C + 1,
  fib_tail(X, NY, NZ, NC, NT).

goal
fib_tail(5 ,0 ,1 ,0, T)
like image 850
Ibrahim Amer Avatar asked Dec 29 '25 22:12

Ibrahim Amer


1 Answers

your second clause fib_tail has 2 flaws:

  • X is never incremented
  • NT is a singleton, thus doesn't 'transmit' any value to the caller.

edit the comment highlight that X doesn't need to be incremented, being compared against the correctly incremented C.

I think you should before try to implement the doubly recursive definition, and when that's working optimize removing the costly call.

like image 172
CapelliC Avatar answered Jan 02 '26 12:01

CapelliC