add(X,n0,X). add(X,Y,Z) :- inc(X,X1),dec(Y,Y1),add(X1,Y1,Z).
In other words, the sum of a number and zero is itself; the sum of X and Y is Z if the increment of X is X1, the decrement of Y is Y1 and the sum of X1 and Y1 is also Z. The strategy is to decrement Y until it reaches zero (only positive numbers of course!), while incrementing X. The first is a fact, the second is a rule.
A simple query is:
?- add(n3,n2,n5).
This goal is replaced by the three subgoals on the right hand side of the rule:
inc(n3,X1),dec(n2,Y1),add(X1,Y1,n5)
the first subgoal is satisfied by X1=n4, and the second by Y1=n1; this leaves:
add(n4,n1,n5)
Again the rule is used:
inc(n4,X1),dec(n1,Y1),add(X1,Y1,n5)
This time X1=5, and Y1=0, so we are left with:
add(n5,n0,n5)
This time the goal matches with the fact and the recursion stops. The goal suceeds.