2017-05-30 63 views
1

在這個序言的例子中,你可以使用遞歸找到任意的Z值,最終檢查某人是否是某人的祖先。然而,如果你想獲得Z的列表來了解導致祖先的父母鏈,那該怎麼辦?你怎麼輸出這個?如何跟蹤序言中的值?

感謝

parent(john,paul).    /* paul is john's parent */ 

parent(paul,tom).    /* tom is paul's parent */ 

parent(tom,mary).    /* mary is tom's parent */  

ancestor(X,Y):- parent(X,Y). /* someone is your ancestor if there are your parent */ 

ancestor(X,Y):- parent(X,Z), /* or somebody is your ancestor if they are the parent */ 
    ancestor(Z,Y). /* of someone who is your ancestor */ 

http://www.doc.gold.ac.uk/~mas02gw/prolog_tutorial/prologpages/recursion.html

+0

比顯式跟蹤更重要的是瞭解程序的終止屬性。你的程序終止**從不**。有關更多信息,請參見[tag:failure-slice]。 – false

回答

0

你可以嘗試建立這樣的名單:

anclist(X, X, []). /* Stop when you get to the end*/ 
anclist(X, Y, [H|T]) :- parent(X, H), ancestor(H, Y), anclist(H, Y, T). 

你叫這樣的:

anclist(john, mary, X). 

,並得到:

X = [paul, tom, mary]