Search code examples
prologsuccessor-arithmetics

Prolog addition excercise


I have this very simple code as a representation of numerals. The problem is when I use the add2 function.

Example: add2(s(0)+s(s(0)), s(s(0)), Z). returns s(s(s(s(s(0))))) correctly. However add2(0, s(0)+s(s(0)), Z). always returns s(0)+s(s(0)). Can anyone see why this is happening?

numeral(0).
numeral(s(X)) :- numeral(X).
numeral(X+Y) :- numeral(X), numeral(Y).

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

%%  exercise 1
add2(X,Y,R) :- add(X,Y,R).
add2(X+Y,Z,R) :- add(X,Y,A),add2(A,Z,R).
add2(X,Y+Z,R) :- add(Y,Z,A),add2(X,A,R).

Solution

  • It's happening because of the combination of the first add2 clause and the first add clause. Your add2(0, ..., ...) will trigger add(0, ..., ...) which always unifies the second and third argument.