I am a beginner at prolog and required to write a predicate path(Start, Dest, Path) for metro stations application using backtracking. Given some facts: connected(x,y) describing the connected stations, I managed to do the following
%% Some facts (for illustration):
connected(a,b).
connected(b,c).
connected(c,d).
connected(d,e).
connected(e,f).
%% Direction A (e.g from b to e)
path1(Start, End, [[Start,End]]):- (connected(Start,End) ; connected(End,Start)),!.
path1(Start, End, [[Start,X]|Path]):-
connected(Start, X),
path1(X, End, Path).
%% Direction B (e.g from f to A)
path2(Start, End, [[Start,End]]):- (connected(Start,End) ; connected(End,Start)),!.
path2(Start, End, [[Start,X]|Path]):-
connected(X, Start),
path2(X, End, Path).
%% And for the required predicate:
path(Start, End, Path):-
path1(Start, End, Path)
;
path2(Start, End, Path).
The above predicates works properly and as required, but what I want to do is to merge these two predicates into a single one in a better way and I don't know exactly how to do so. Anyone can help?
Thanks in advance.
EDIT:
I modified it to the following:
path(Start, End, [[Start,End]], _):- (connected(Start,End) ; connected(End,Start)),!.
path(Start, End, [[Start,X]|Path], Direction):-
(Direction == 0,
connected(Start, X),
path(X, End, Path,0))
;
(Direction == 1,
connected(X, Start),
path(X, End, Path,1))
%% And for the required predicate:
path(Start, End, Path):-
path(Start, End, Path, 0)
;
path(Start, End, Path, 1).
but still need to remove more of the repetitive code lines.
path1andpath2predicates. I merged them usingpath, but you can see that they are the same predict with only changing the order of arguments inconnected. I'm seeking to find a wat that makes me write only one predicate to act the same as the above code. @WillNess - Khalid