Information Technology Reference
In-Depth Information
Figure 3.5.
Negative queries after loading the family.pl program
?-
child(john,george).
% Is John a child of George?
No
?-
\+ child(john,george).
% Is John not a child of George?
Yes
?-
parent(X,john), female(X).
% Who is a parent of John
X = sue
% and female?
Yes
?-
parent(X,john), \+ female(X).
% Who is a parent of John
X = sam
% and not female?
Yes
3.
Otherwise, use back-chaining to try to establish
P
1
, then
P
2
, then . . .
P
n
.
If these are all successful, then return
success
.
This attempt to handle
P
1
,
then
P
2
,
and so on, is treating the body of a conditional sen-
tence like a conjunctive query: they all have to succeed for this use of the conditional
sentence to be successful. In fact, if the clause
daughter(F,X) :- female(F), parent(X,F).
had been included in the Prolog program of figure 3.1, the query
daughter(F,sam)
could have been used instead of the second conjunctive query in figure 3.4 to find a
female that Sam is a parent of.
3.2.3 Negation in queries
Prolog also allows
negated queries
. The special symbol
\+
(meaning
not
) can be used
in front of an atom in a query to flip from a
Yes
to a
No
, and vice versa. Consider
figure 3.5. The answer to the second query is the opposite of the answer to the first
one. By itself, this is not very useful. It becomes more useful in the context of a
conjunctive query like the fourth one in the figure, where the user wants to find a
parent of John who is
not
female.
There was nothing like this use of negation in chapter 2. The query
male(X)
could
have been used, but observe that this is not quite the same as
\+ female(X)
. Consider
the case of
gina
, for example. Because the queries
male(gina)
and
female(gina)
both
fail
(since the sex of Gina is not specified), the query
\+ female(gina)
will succeed,
whereas
male(gina)
will fail.