Matthias Neubert
Matthias Neubert

Reputation: 335

How to make a negative fact in PROLOG

If I have a fact "Anna is a person" in PROLOG I write for example:

person(anna).

But what do I write if I have a fact "table is not a Person". I tried

not(person(table)).

But this doesn't work. How do I write negative facts?

Upvotes: 3

Views: 2528

Answers (2)

Radacina
Radacina

Reputation: 441

Actually you could use a rule like person(table):-false.

Upvotes: 3

lurker
lurker

Reputation: 58324

In Prolog, typically you don't have to assert the negative as a fact. The absence of the positive fact or a proving rule results in failure (or more accurately, "lack of provability").

So if you only assert that person(anna), then the query person(anna). will be true (succeed, or be provable), but person(table). will be false (fail, or is not provable) as expected. Also, the query, person(X). will only yield X = anna as expected.

By default, if you query person(X) and there are no persons defined, Prolog will give an error indicating that person is an unknown predicate. If you would rather that Prolog simply fails in that case, there's an option you can set (I know in SWI Prolog in particular, but I don't recall what the option is), or you can declare person/1 to be a dynamic predicate if you plan to assert person facts into your database dynamically as the program executes.

As part of a predicate definition, you might want to indicate that a warm-blooded animal is a mammal but is not a person. In that case, you might have:

warm_blooded_animal(X) :-
    mammal(X),
    \+ person(X).

This is a little contrived just as an example. In this case, you'd more likely define mammal in terms of the characteristic of being warm-blooded, etc, rather than the other way around. But you get the idea... Note that the operator not/1 is deprecated in favor of the ISO standard \+/1.

Upvotes: 4

Related Questions