Recursive Fibonacci Functor

I am new to Prolog and I need help with this functor calculates the Fibonacci numbers ... first it adds Y = 0 and Z = 1, then it calls itself Y = Z and Z = Y + Z and every time it increases the value of counter C as long as the counter is X ..... the problem is that the result is always 1, because the prolog never executes the second sentence, even if X is not equal to M, but I don’t know why. ....

X: calculate the Fibonacci value Y: the first number in the Fibonacci series Z: the second number in the Fibonacci series C: the counter with 0 as the value intial 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) 
+4
source share
1 answer

your second fib_tail clause has 2 drawbacks:

  • X never increases.
  • NT is singleton, so it does not pass any value to the caller.

edit comment emphasizes that X does not need to be enlarged by comparing with correctly enlarged C.

I think you need to before you try to implement a twice recursive definition, and when this work optimizes the removal of an expensive call.

+3
source

Source: https://habr.com/ru/post/1442831/


All Articles