next up previous contents
Next: Cut Up: Introduction to logic programming Previous: Arithmetic   Contents

Negation as failure

In Prolog, we can write a premise of the form not(R(X,Y,Z)). This becomes true if Prolog is not able to justify R(X,Y,Z). In other words, for each relation Prolog uses a ``closed world'' assumption--the rules and facts exhaustively determine all the members of the relation and anything that is not computable as being part of the relation is out of the relation. This approach is called ``negation as failure''.

Negation has some unexpected effects. For instance, consider the following query.

  ?- not(X=5).
  No.

The No is justified as follows. To check not(X=5), Prolog first tries the goal X=5. Since X can be unified with 5, this goal succeeds. Therefore, not(X=5) fails.

Now, consider a query to extract from a list Ls all elements that are not equal to 1. We could write it two ways:

?-  not(X=1), member(X,Ls).

?-  member(X,Ls), not(X=1).

In the first version, not(X=1) always fails, as we saw above, because X is not bound to any value initially. This results in the query failing. The second query, however, does the job that we want because X is first bound to an element of Ls before being tested for X=1.


next up previous contents
Next: Cut Up: Introduction to logic programming Previous: Arithmetic   Contents
Madhavan Mukund 2004-04-29