追踪序言递归深度的方法?

时间:2016-10-15 03:34:01

标签: recursion prolog

在prolog中

我的数据库设置如下

male("John").
male("Bob").
male("Billy").
male("Gary").

Parent("Bob","John").
Parent("Billy","Bob").
Parent("Gary", "Billy").


ancestor(Ancestor, Descendant) :-
    parent(Ancestor, Descendant).
ancestor(Ancestor, Descendant) :-
    parent(Ancestor, CommonAncestor),
    ancestor(CommonAncestor, Descendant).

是否可以跟踪此祖先函数的递归距离?例如,如果我们运行

?- ancestor("Billy", "John", X).

是否可以让X返回2,或者在

的情况下
?- ancestor("Bob", "John", X).

让X返回1?

1 个答案:

答案 0 :(得分:2)

你好写道:

ancestor(Ancestor, Descendant,1) :-
    parent(Ancestor, Descendant).
ancestor(Ancestor, Descendant,X) :-
    parent(Ancestor, CommonAncestor),
    ancestor(CommonAncestor, Descendant,X1),
    X is X1+1.

一些例子:

?- ancestor("Billy", "John", X).
X = 2 ;
false.

?- ancestor("Bob", "John", X).
X = 1 ;
false.