Recursive function in Prolog

I am trying to compute a 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 get true / false. How to calculate the value of this function?

Many thanks!

+3


source to share


2 answers


Your last rule looks a little strange to me. I would try something like this:



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

      

+1


source


You can easily turn this into a true relation by simply using 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).

      



An example of a request and its result:

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

      

+3


source







All Articles