问题
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:
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).
来源:https://stackoverflow.com/questions/65063263/prolog-construct-a-transitive-closure-of-a-graph