Prolog recursion using s(0) and p(0)

153 views Asked by At

I have the following code below to add s(0) (Representing the successor of 0) and p(0) (Representing the predecessor of 0). However when I run the query listed below, the output is Z = p(s(s(s(s(0)))) when it should just be Z = s(s(s(0))) as the p(0) can be cancelled out by one s(0). I am not sure why the recursion is not working properly and any help would be greatly appreciated.

?- add3(p(0)+s(s(0)),s(s(0)),Z). 

Here is the code for the knowledge base:

% Original add
add(0,X,X).
add(s(X),Y,s(Z)) :- add(X,Y,Z).
add(p(X), Y, p(Z)) :- add(X,Y,Z).

% Base case when 0 cannot be broken down further
simple(0,0).
simple(p(s(0)), 0).
simple(s(p(0)), 0).

% Change to make to simplify expression

simple(s(X),s(Y)) :-
    simple(X,Y).

simple(p(X), p(Y)) :-
    simple(X, Y).

% Case if X+Y
simple(X+Y,Z) :-
    simple(X,XS),
    simple(Y,YS),
    add(XS,YS,Z).

% add3
add3(A,B,C) :-
    simple(A,RA),
    simple(B,RB),
    add(RA,RB,C).
1

There are 1 answers

0
ggplot2 On

Not too worry, I actually found a solution.

I changed the base case to these three:

simple(0, 0).
simple(p(s(X)), X).
simple(s(p(X)), X).

It seemed to work