prologexponentiationfailure-slicesuccessor-arithmeticsnon-termination

Prolog predicate - infinite loop


I need to create a Prolog predicate for power of 2, with the natural numbers. Natural numbers are: 0, s(0), s(s(0)) ans so on..

For example:

?- pow2(s(0),P).
P = s(s(0));
false.
?- pow2(P,s(s(0))).
P = s(0);
false.

This is my code:

times2(X,Y) :-
  add(X,X,Y).

pow2(0,s(0)).
pow2(s(N),Y) :-
  pow2(N,Z),
  times2(Z,Y).

And it works perfectly with the first example, but enters an infinite loop in the second..
How can I fix this?


Solution

  • This happends because the of evaluation order of pow2. If you switch the order of pow2, you'll have the first example stuck in infinite loop.. So you can check first if Y is a var or nonvar.

    Like so:

    times2(X,Y) :-
      add(X,X,Y).
    
    pow2(0,s(0)).
    pow2(s(N),Y) :-
      var(Y),
      pow2(N,Z),
      times2(Z,Y).
    pow2(s(N),Y) :-
      nonvar(Y),
      times2(Z,Y),
      pow2(N,Z).