2016-10-15 53 views
1

我有我的數據庫建立這樣跟蹤序言遞歸深度的方法?在序言

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的回報?

回答

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.