recursion and the order of terms in a PROLOG clause
Lets look at two logically correct ways of encoding the ancestor relation 1. a program that works as desired 2. one that will sometimes loop infinitely Abbreviations: a=ancestor p=parent
1.A version that works p(h,t). p(t,j). (just three generations) a(X,Y) :- p(X,Y). a(X,Y) :- p(X,Z),a(Z,Y) Query: :- a(h,h). Run PROLOG: :- p(h,Z),a(Z,h). Only one choice: :- p(h,t),a(t,h). :- p(h,t),p(t,Z),a(Z,h). Only one choice! :- p(h,t),p(t,j),a(j,h). :- p(h,t),p(t,j),p(j,Z),a(Z,h). FALSE!
2. A version that can loop p(h,t). p(t,j). a(X,Y) :- p(X,Y). a(X,Y) :- a(X,Z),p(Z,Y) Query: :- a(h,h). Run PROLOG: :- a(h,Z1),p(Z1,h). :- p(h,t),p(t,h). FALSE :- a(h,Z2),p(Z2,Z1),p(Z1,h). :- p(h,t),p(t,Z1),p(Z1,h). FALSE :- a(h,Z3),p(Z3,Z2),p(Z2,Z1),p(Z1,h). Etc.
This was another illustration of how the order between the terms in a clause can affect the meaning of a PROLOG program