Prolog: Get object or objects that do not comply a

2019-07-31 09:38发布

Suppose I have the following facts:

boy(a).
boy(b).
girl(c).
girl(d).

If I query:

?-boy(X).

I get:

X=a;
X=b.

Which query should I use using a variable to get the objects that do not comply with the rule boy(), in this case, c and d?

I am new to Prolog, so I was thinking about using

?-not(boy(X)).

But that is not correct. Im using swi-prolog. Thanks in advance for your time and help.

标签: prolog
1条回答
贪生不怕死
2楼-- · 2019-07-31 10:13

The problem with not(boy(X)) is that Prolog doesn't know what the "universe of possible choices" are for X in order to then test if they're a boy. The boy facts only know boys, of course.

One approach is to define all people in addition to the gender. For example:

% Define people

person(a).
person(b).
person(c).
person(d).

% Define genders

boy(a).
boy(b).
girl(c).
girl(d).

Then to check for all "non-boys" you would do:

?- person(X), not(boy(X)).

Depending upon how you want to organize your data, you can combine gender with person:

person(a, boy).
person(b, boy).
person(c, girl).
person(d, girl).

Then query:

?- dif(Y, boy), person(X, Y).

Or write it as a predicate:

person_not_of_gender(Person, Gender) :-
    dif(OtherGender, Gender),
    person(Person, OtherGender).

Then query:

?- person_not_of_gender(Person, boy).
查看更多
登录 后发表回答