Search code examples
functionrecursionprologclpfd

Recursive function in Prolog


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!


Solution

  • 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.