You may want to make the success of a particular goal contingent on
the failure of some subgoal. This can be done using the built in \+
operator. For example, in code Section 13.1 file
there is a predicate possible_to_marry(A,B)
which states that ``It is
possible for A to marry B if A is male and B is female and A is not
related to B''. The code for this is:
possible_to_marry(A, B):- male(A), female(B), \+ related(A, B).Note that
\+
is a prefix operator which, in this case, takes
related(A,B)
as its argument.
An important point to note about negation in Prolog is that it doesn't
mean that the goal you have negated is proved false in the logical
sense. It does mean that the goal can not be established from the
current set of axioms in the database. The implicit assumption here
is that the set of axioms in the current database are a complete
description of every aspect of the problem. This is often referred to
as the closed world assumption.
This rather liberal interpretation of negation can be used to express
defaults. For example we might have a problem in which we could
identify all females by name, using the predicate female/1
to denote
that someone is female:
female(alice). female(betty). ...etc.and, given that we have recorded the names of all females, we might want to assume that anyone who wasn't a known female was male. We could do this using the rule:
male(X):- \+ female(X).Now the goal
|?- male(alice).
will fail because
female(alice)
is true and so \+ female(alice)
must fail.
Conversely, the goal |?- male(fred).
will succeed because there
is no way to establish female(fred)
and so
\+female(fred)
succeeds.
However, you have to be careful when exploiting the closed world
assumption in this way because someone may subsequently run your
program without being aware of this limitation. For example, I happen
to know that 'minnie mouse'
is female but the program in our example
will happily allow the goal |?- male('minnie mouse').
to succeed.