Reputation: 49
I am new to Prolog. I am trying to write a predicate that is true when there is a path from X to Z, including X to Y and Y to Z.
For example
foo(b,Y,[[a,b],[b,c],[b,d],[d,e]]).
Y = c ;
Y = d ;
Y = e ;
I can write the code which is true when there is a path from X to Y but can't figure out how to add the code to get from Y to Z if the base case is true.
foo(Y, X, [Y, X]).
foo(Y, X, [Head|_]) :- foo(Y, X, Head).
foo(Y, X, [_|Tail]) :- foo(Y, X, Tail).
Upvotes: 2
Views: 190
Reputation: 10102
(Assuming you want general transitive closure)
conn(XYss, X, Y) :-
member([X,Y], XYss).
foo2(X, Y, XYss) :-
closure(conn(XYss), X, Y).
using closure/3
. Alternatively, using library(lambda)
:
foo2(X, Y, XYss) :-
closure({XYss}+\Xi^Yi^member([Xi,Yi], XYss), X, Y).
And taking your question literally, you only want:
foo3(X, Y, XYss) :-
member([X,Y], XYss).
foo3(X, Z, XYss) :-
member([X,Y], XYss),
member([Y,Z], XYss).
Upvotes: 2