Back Top Forward

Prolog can actually do arithmetic only knowing basic facts about "what comes next". Integers can be represented by Prolog atoms: n0, n1, n2 etc. The increment function can be defined as a set of relations between integers as follows:

inc(n0,n1).
inc(n1,n2).
inc(n2,n3).
inc(n3,n4).
inc(n4,n5).
inc(n5,n6).
inc(n6,n7).
inc(n7,n8).
inc(n8,n9).
inc(n9,n10).

Note that we will only consider positive integers between zero and ten, since there are actually an infinite number of relations. If we ever try to find the number whose increment is zero, we will fail. Similarly, the increment of any number past ten will also fail. This means that we can only do general arithmetic in theory, but considering that most programming languages restrict the size of integers anyway, we are not completely off base.

Sample queries that we can put to Prolog concerning these facts are:

A direct match with a fact:

?- inc(n2,n3).
 yes

None of the facts match:

?- inc(n4,n6).
 no

A fact, although true, is unknown to Prolog (Closed World Assumption)

?- inc(n11,n12).
 no

A variable: "is there an X such that its increment is 5". Prolog searches the facts in turn until a match is found.

?- inc(X,n5).
 X=n4 

The same, but asking Prolog for resatisfaction (by typing a semicolon). The search is continued from the point it left off. There are no further solutions.

?- inc(X,n5).
 X=n4;
 no
A variable with a no result:
?- inc(X,n12).
   no

Two variables, and restasfaction after each answer:

?- inc(X,Y).
   X=n0,Y=n1;
   X=n1,Y=n2;
   ...
   X=n9,Y=n10;
   no