I was looking at this question, in which we make a predicate in Prolog which finds a path between two nodes ("metro stations") in a directed graph. The original code suggested is the following
path(Start, Dest, [[Start,Dest]]) :- connected(Start, Dest).
path(Start, Dest, [[Start, Waypoint]|Path]) :- dif(Dest, Waypoint),
connected(Start, Waypoint), path(Waypoint, Dest, Path).
However, in order to deal with loops, and eliminate lists which contain them, I tried along the recursion store the stations in which I stopped already, and to check that I don't repeat any of them. This is the code I came up with (note that I don't make a list of lists, rather a list of the stations themselves)
alldifferent(_,[]).
alldifferent(X,[L|Ls]) :- dif(X,L), alldifferent(X,Ls).
pathaux(Start, Dest, [Start,Dest],Q) :- connected(Start, Dest), alldifferent(Start,Q).
pathaux(Start, Dest, [Start, Waypoint|Path],Q) :- dif(Dest, Waypoint),
connected(Start, Waypoint),
pathaux(Waypoint, Dest, Path, [Start|Q]), alldifferent(Start,Q).
path(X,Y,Z) :- pathaux(X,Y,Z,[]).
However, when I add a rule which creates a loop
connected(ataba,naguib).
connected(naguib,sadat).
connected(sadat,opera).
connected(opera,dokki).
connected(opera,ataba). //Note this one
I get an infinite recursion! how come? and how can one fix this?