52 Logic Programming With Prolog
3.5 Removing Common Variables
When unifying a goal with a head of a clause, there is an important complication,
which all the examples in this chapter so far have been carefully designed to avoid:
what happens if the goal and the head have one or more variables in common?
Suppose that the goal is mypred(tuesday,likes(Z,Y),X) and the head is
mypred(X,Y,Z). The variables X, Y and Z in the former appear to be the same as
the variables X, Y and Z in the latter, but in fact there is no connection between
them. The clause of which mypred(X,Y,Z) is the head may be, for example,
mypred(X,Y,Z):-pred2(X,Q),pred3(Q,Y,Z).
The variables in this rule are just 'placeholders'. They can be replaced
consistently by any other variables without any change in the meaning of the
clause, as explained in Chapter 2, so it would not be sensible to consider X, Y and Z
in the clause to be the same variables as in the goal
mypred(tuesday,likes(Z,Y),X).
Before attempting to unify the goal and the head of the clause, it is first
necessary to rewrite the clause to ensure that it has no variables in common with
the goal. To be precise the clause must not have any variables in common with any
of the goals in the sequence of which the goal currently under consideration is part.
Prolog automatically replaces variables X, Y and Z in the clause systematically
by other variables that do not appear in the sequence of goals (or elsewhere in the
clause). For example they may be replaced by X1, Y1 and Z1.
mypred(X1,Y1,Z1):-pred2(X1,Q),pred3(Q,Y1,Z1).
After this rewriting it is only necessary to unify the head mypred(X1,Y1,Z1)
and the goal mypred(tuesday,likes(Z,Y),X), which have no variable in common.
The unification succeeds.
mypred(tuesday,likes(Z,Y),X)
mypred(X1,Y1,Z1):-pred2(X1,Q),pred3(Q,Y1,Z1).
Succeeds with variable X1 bound to atom tuesday, variable Y1 bound to
compound term likes(Z,Y) and variables Z1 and X bound to each other.
Variables Y and Z are unbound.
3.6 A Note on Declarative Programming
From this chapter it is clear that the order in which the clauses defining a predicate
occur in the database and the order of the goals in the body of a rule are of vital
importance when evaluating a user's query.