0

A single query to complete my program should check if there is a direct route between two given cities. Alternatively, it can list all the connected cities for a given city. See the following:

flight(city1,city2).
flight(city2,city1).
flight(city2,city3).
flight(city3,city2).

My predicates:

route(X,Y):-
    flight(X,Y).
route(X,Y) :- 
    flight(X,Z),    
    route(Z,Y).

My result :

?- route(city1,X).
X = city2 ;
X = city1 ;
X = city3 ;
X = city2 ;
X = city1 ;
X = city3 ;
X = city2 ;
X = city1 ;
X = .......

But i have infinitie recursion , and it can not stop. What can i solve this problem ?

Guy Coder
  • 24,501
  • 8
  • 71
  • 136
mbnld
  • 51
  • 1
  • 6
  • 1
    You state that for all X, Y, there is a route between X and Y: `route(X,Y)`. Very weird. `route(ms_harrisons_kitchen,arthurs_library).` yields `true` for example. Please reconsider. – David Tonhofer Jan 11 '20 at 18:28
  • 1
    Use [`closure0(flight, X,Y)`](https://stackoverflow.com/q/26946133/772868). – false Jan 11 '20 at 18:35
  • I edited my code @DavidTonhofer , above.. – mbnld Jan 11 '20 at 18:55
  • @MesutBUNALDI Thanks, I have updated the "as is" printout. – David Tonhofer Jan 11 '20 at 19:26
  • The problem is that what you are doing is a graph search for "reachability", but you are not checking whether a node in the graph has already been visited earlier. Thus `city1->city2` is found, then `city1->city2->city1` is found, `city1->city2->city3` is found, `city1->city2->city1->city2` is found etc etc. You need to also collect the visited cities in a list and check whether the city has been visited already, and if so, stop the recursive descent. You can also flamethrower the problem and use the solution by @false, but that's probably not the idea of the exercise. – David Tonhofer Jan 11 '20 at 19:32
  • actually my idea is ; i have to get a list. so my result must be ; x= city1 x=city2 and done – mbnld Jan 11 '20 at 19:40
  • @Mesut: Please consult the link above, it contains all you ever need. And no it's not a flamethrower, but just the perfect tool. – false Jan 11 '20 at 19:41
  • @false i looked but i dont understand , i confused :( – mbnld Jan 11 '20 at 19:44
  • @Mesut: Try it out, first – false Jan 11 '20 at 19:52
  • 1
    @false i included your closure0 to my project it worked. thanks :) – mbnld Jan 11 '20 at 20:01
  • @false can i find shortest path value in my graph with closure0 ? my facts are like : distance(city1,city2,100). ... and i want to shortval(distance , cityX,cityY,D). and get shortest distance value – mbnld Jan 12 '20 at 18:49
  • @Mesut: You are now changing the subject. First, you wanted transitive closure without looping. But now you want something different. Please look an existing questions or ask a new question. – false Jan 12 '20 at 20:26

0 Answers0