Select list out of a list?

2019-09-11 21:05发布

问题:

I have a list of persons and parent facts

person(nameA).
person(nameB).
person(nameC).

parent(parentname, children).

I need to write a rule hasnochild(X). to iterates through all person that has no child.

This is what I have wrote thus far. hasnochild(X) :- parent(Z, X). But it returns all the person's name who has a child. How do I get those who have no child?

Something like the whole list of person minus off what I have wrote.

回答1:

You have to try to unify Person (X in your question) with a person in the database, then succeed only if that person does not have children.

E.g.:

hasnochild(X):-
  person(X),         % X is a Person
  \+ parent(X, _).  % with no children

The call to person(X) may be avoided if you know that the first argument to parent/2 is a person.



标签: prolog