2

I'm very new to Prolog. I have such a graph:

edge(a,e).
edge(e,f).
edge(f,d).
edge(d,a).

I define a transitive closure as:

p(X,Y) :- edge(X,Y).
tran(X,Z) :- p(X,Y), p(Y,Z).

I need to construct a transitive closure of a graph. Please let me know how to proceed with it.

vlad-kom
  • 21
  • 1
  • Does this answer your question? [How to express "ancestor" recursively](https://stackoverflow.com/questions/64048419/how-to-express-ancestor-recursively) – MWB Nov 29 '20 at 23:00

1 Answers1

2

The problem with trans/2 is that it will only walk two edges, not an arbitrary number.

We can define a predicate tran(X, Z) that holds if edge(X, Z) holds, or edge(X, Y) and then tran(Y, Z). We thus in the latter follow one edge and then recurse on tran/2:

tran(X, Z) :-
    edge(X, Z).
tran(X, Z) :-
    edge(X, Y),
    tran(Y, Z).
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555