本文介绍了Prolog和祖先关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须编写一个小的序言程序来检查给定的人是否是第二个人的祖先.这些是事实和规则:

I have to write a small prolog program which checks if a given person is a ancestor of a second one.These are the facts and rules:

mother(tim, anna).
mother(anna, fanny).
mother(daniel, fanny).
mother(celine, gertrude).
father(tim, bernd).
father(anna, ephraim).
father(daniel, ephraim).
father(celine, daniel).

parent(X,Y) :- mother(X,Y).
parent(X,Y) :- father(X,Y).

判断一个人是否是另一个人的祖先很容易:

The test if a person is an ancestor of another person is easy:

ancestor(X, Y) :- parent(X, Y).
ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y).

但是现在我必须编写一个方法祖先(X,Y,Z),它还可以打印出两个人之间的关系.它应该是这样的

But now I have to write a method ancestor(X,Y,Z) which also prints out the relationship between two persons. It should look like this

?- ancestor(ephraim, tim, X).
false.
?- ancestor(tim, ephraim, X).
X = father(mother(tim)).

这就是问题所在:我不知道该怎么做.

And that is the problem: I have no clue how do to this.

推荐答案

您可以使用累加器来适应@Scott Hunter 的解决方案:

You can use an accumulator to adapt @Scott Hunter's solution :

mother(anna, fanny).
mother(daniel, fanny).
mother(celine, gertrude).
father(tim, bernd).
father(anna, ephraim).
father(daniel, ephraim).
father(celine, daniel).

ancestor(X, Y, Z) :- ancestor(X, Y, X, Z).
ancestor(X, Y, Acc, father(Acc)) :- father(X, Y).
ancestor(X, Y, Acc, mother(Acc)) :- mother(X, Y).
ancestor(X, Y, Acc, Result) :-
    father(X, Z),
    ancestor(Z, Y, father(Acc), Result).
ancestor(X, Y, Acc, Result) :-
    mother(X, Z),
    ancestor(Z, Y, mother(Acc), Result).

edit :正如 Scott Hunter 在他的编辑中所展示的,这里不需要显式的累加器,因为我们可以在每次迭代时轻松地让术语的内部部分不受约束.因此他的解决方案更好!

edit : as Scott Hunter showed in his edit, there's no need for an explicit accumulator here, since we can left the inner part of the term unbound easily at each iteration. His solution is therefore better !

这篇关于Prolog和祖先关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 15:56