我的数据库设置如下
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?
答案 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.