2017-05-30 62 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]