2

I cannot understand why false is returned for jordan but not for china:

When I query:

countries_visited(jordan, X).

I get a return of amman and false.

But when I query

countries_visited(china, X).

I get a return of beijing and shanghai.

city_in_country(amman, jordan).    
city_in_country(shanghai, china).    
city_in_country(beijing, china).    
city_in_country(brussels, belgium).    
city_in_country(london, uk).    
city_in_country(manchester, uk).

city_visited(amman).    
city_visited(beijing).    
city_visited(shanghai).    
city_visited(cairo).    

countries_visited(ThisCountry, ThisCity) :- 
    city_visited(ThisCity), 
    city_in_country(ThisCity, ThisCountry).
repeat
  • 18,496
  • 4
  • 54
  • 166
benji247
  • 21
  • 2
  • In one word: [backtracking](https://en.wikipedia.org/wiki/Backtracking) – Guy Coder Feb 14 '19 at 17:05
  • 2
    In Prolog, if the logic indicates there *may* be more solutions (*i.e.*, there's a choice point), Prolog will backtrack looking for more. If it finds no more, it ultimately fails to do so (and outputs `false`). Your `countries_visited(jordan, X).` query is one of those cases. After finding `X = amman`, Prolog looks for more solutions and finds none, so it then says `false`. In the case of your query `countries_visited(china, X).` it does the same thing after finding the two solutions, at least when I tried it. I got `X = bejing` then `X = shanghai`, then `false. – lurker Feb 14 '19 at 17:07
  • This called a spurious choice point. They're pretty common, usually nothing to be alarmed about. They don't indicate an error or a mistake. – Daniel Lyons Feb 14 '19 at 17:16
  • @Dan: leftover choicepoint – false Feb 14 '19 at 19:09
  • Hmm. That is interesting. I was using swish.swi-prolog.org and my results were inconsistent. It makes sense now you mention backtracking, but my inconsistent results are still baffling. – benji247 Feb 15 '19 at 10:52

0 Answers0