Sunday 18 January 2009

Order of Clauses and Goals: Infinite Loops

Consider the following clause:
P:-p.
This means ‘p is true if p is true’. This is declaratively perfectly correct, but procedurally is quite useless.
?-p.
Using the clause above, the goal p is replaced by the same goal p; this will be in turn replaced by p, etc. Prolog will enter an infinite loop not noticing that no progress is being made.
Any differences in order of the clauses may cause finite loops. For example you can’t move if you don’t get up.


Different variation of clauses produces different answers.
The predecessor procedure consists of two clauses, and one of them has two goals in the body. There are,therefore, 4 variations of this program, which have the same declarative meaning, can be obtained by:
Swapping both clauses, and
Swapping the goals for each order of clause.


The Original version:
pred1(X, Z) :- parent(X, Z).
pred1(X, Z) :- parent(X, Y), pred1( Y, Z).
Variation a:
pred2(X, Z) :- parent(X, Y), pred2( Y, Z).
pred2(X, Z) :- parent(X, Z).
Variation b:
pred3(X, Z) :- parent(X, Z).
pred3(X, Z) :- pred3( X, Y), parent(Y, Z).
Variation c:
pred4(X, Z) :- pred4( X, Y), parent(Y, Z).
pred4(X, Z) :- parent(X, Z).



Let’s see what happens if we ask whether Tom is a predecessor of Pat using the four variations of the predecessor relation:

?- pred1(tom, pat).
yes

?- pred2(tom, pat).
yes

?- pred3(tom, pat).
yes

?- pred4(tom, pat).

Prolog can not find the answer and this is manifested on the terminal by a Prolog message such as “More core needed” or “Stack Overflow”.

No comments:

Post a Comment