序言和祖先关系 [英] Prolog and ancestor relationship

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

问题描述

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

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).

但是现在我必须写一个方法ancestor(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 !

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆