Type the edge facts and the acyclic path finder
Type the edge facts and the acyclic path finder
Answer
edge(a,b). edge(a,c). edge(b,d). edge(c,d). edge(d,e). path(G, G, V, P) :- reverse(V, P). path(N, G, V, P) :- edge(N, Nx), \+ member(Nx, V), path(Nx, G, [Nx|V], P).
Base case: current node equals goal G, so reverse the accumulated visited list V into the forward path P. Recursive step: take an edge N->Nx, require Nx is unvisited (the cycle guard), and recurse with Nx prepended. Prepend-then-reverse keeps each step O(1).