Recursive function in Prolog

245 views Asked by At

I try to calculate recursive function:

f(x, y) = 0 if x = 0;
f(x, y) = 1 if x = 1;
f(x, y) = y*y*f(x-2,y) if x>1.

I tried this way:

f(0,_,0).
f(1,_,1).
f(X,Y,Z):-
          X>1,
          XX is X-2,
          ZZ = Y*Y*Z,
          f(XX,Y,ZZ).

I can only obtain true/false. How can I calculate value of this function?

Thank you very much!

2

There are 2 answers

0
Ted Hopp On BEST ANSWER

Your last rule looks a little odd to me. I'd try something like this:

f(X,Y,Z) :-
    X > 1,
    XX is X-2,
    f(XX,Y,ZZ),
    Z is Y * Y * ZZ.
0
mat On

You can easily turn this into a true relation if you simply use CLP(FD) constraints:

:- use_module(library(clpfd)).

f(0, _, 0).
f(1, _, 1).
f(X, Y, Z):-
        X #> 1,
        XX #= X-2,
        Z #= Y*Y*ZZ,
        f(XX, Y, ZZ).

Example query and its result:

?- f(X, 5, Z).
X = Z, Z = 0 ;
X = Z, Z = 1 ;
X = 2, Z = 0 ;
X = 3, Z = 25 .