I need a predicate routing which gives all the cities between start & end. For example:
path(chicago,atlanta).
path(chicago,milwaukee).
path(milwaukee,detroit).
path(milwaukee,newyork).
path(chicago,detroit).
path(detroit, newyork).
path(newyork, boston).
path(atlanta,boston).
path(atlanta, milwaukee).
?- routing(chicago,newyork,X).
X=[chicago,milwaukee,newyork];
X=[chicago,detroit,newyork];
X=[chicago,milwaukee,detroit,newyork];
X=[chicago,atlanta,milwaukee,newyork];
X=[chicago,atlanta,milwaukee,detroit,newyork]
I have tried this, and keep coming back to it.
routing(FromCity,ToCity,[FromCity|ToCity]) :-
path(FromCity,ToCity).
routing(FromCity,ToCity,[FromCity|Connections]) :-
path(FromCity,FromConnection),
path(FromConnection,ToConnection),
path(ToConnection,ToCity),
routing(ToConnection,ToCity,Connections).
routing(FromCity,ToCity,[]).
but it just keeps giving
X=[chicago,milwaukee,newyork];
X=[chicago,chicago,newyork];
X=[chicago,chicago,chicago,newyork]
...
..
Can some one please point me in the right direction …
If you are sure (by definition) that your graph is acyclic, you can simplify your rule, exploiting Prolog depth first search:
This find all availables paths on backtracking:
Note the difference between the first and second pattern of list construction:
[FromCity, ToCity]vs[FromCity|Connections]. This becauseConnectionswill be alist, whileToCitywill be an atom, when the rule will succeed.If your graph contains cycles, this code will loop. You can refer to another answer for a simple schema that handles this problem.