Prolog. Construct a transitive closure of a graph

613 Views Asked by At

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.

1

There are 1 best solutions below

3
On

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).