prologtransitive-closure

Ancestor to all reachable node


I wrote it as such. But it only succeed in finding till the grandparent, and not any further. How do I write it in such a way that it finds all possible ancestor. That is, finding greatgrandparent and even further if there exist such fact?

 ancestor(X, Y) :- parent(X, Y); parent(X,Z), parent(Z,Y).

Given

parent(greatgrand_parent, grand_parent).
parent(grand_parent, parent).
parent(parent, child).

Returns only

?- ancestor(What, child).
What = parent ;
What = grand_parent ;
false.

Solution

  • you forget the recursive call: try

    ancestor(X, Y) :- parent(X, Y) ; parent(X,Z), ancestor(Z,Y).
    

    and you get

    ?- ancestor(X,child).
       X = parent
    ;  X = greatgrand_parent
    ;  X = grand_parent
    ;  false.