问题
I am a newbie to Prolog, and have a question regarding programming a "chain rule" for step-siblings that share a "common parent".
In my program, I am assuming that the existence of the parent(X,Y) fact that asserts that X is a parent of Y.
I need a rule chain(X,Y,L): if X is an ancestor of Y, then L is the list containing X, Y and all ancestors of Y who are also descendants of X, listed in descending order of age (oldest first). In other words, my list should contain all the people that link a person with an ancestor.
Eg: If chain(peter,mary,[peter,paul,sue,mary]), then peter is the parent of paul, paul is the parent of sue, and sue is the parent of mary.
Note: I am familiar with the stepSibling(a,b) relationship where their relationship is qualified via their parents partner(X,Y); where siblings a and b are children of their respective parents via the relationship child(a,X) and child(b,Y). Hence; I am only confused with the relationship where both stepsiblings share a common parent. ie. A child relationship that may look like this: child(a,X) and child(b,X).
回答1:
This is kind of an interesting twist on the usual genealogy problems we discuss in early Prolog courses. Let's consider a simplification first, ancestor(X,Y)
is true if X is an ancestor of Y.
So you have a predicate parent(X,Y)
which says X is a parent of Y. You can write ancestor/2
like this:
% base case: your parent is an ancestor
ancestor(X, Y) :- parent(X, Y).
ancestor(X, Z) :- parent(X, Y), ancestor(Y, Z).
With a sample database like this it should work fine:
parent(peter, paul).
parent(paul, sue).
parent(sue, mary).
This will work for a query like ancestor(peter, mary)
, which is close to what you want. The next step would be to retain the chain, which would look something like this:
chain(X, Y, [X,Y]) :- parent(X, Y).
chain(X, Z, [X|Chain]) :- parent(X, Y), chain(Y, Z, Chain).
This appears to work:
?- chain(peter, mary, X).
X = [peter, paul, sue, mary] ;
false.
I worry though, because your question mentions step siblings and that the chain should include other people. Is that just chaff or do you have additional requirements? If so, they're not reflected in your example, so I may need you to augment your question with additional details.
来源:https://stackoverflow.com/questions/24948401/prolog-chain-rule-for-step-siblings