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.
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 ifedge(X, Z)
holds, oredge(X, Y)
and thentran(Y, Z)
. We thus in the latter follow one edge and then recurse ontran/2
: