1

I am just beginning to learn Prolog:

% Doors

door(kitchen, office).

connect(X, Y) :- door(X, Y).
connect(X, Y) :- door(Y, X).

Now, when I consult:

?- connect(kitchen, office).
true ;
false.

?- connect(office, kitchen).
true.

?-

Why in the first query Prolog thought there's more, and had me press ; ?

Will Ness
  • 70,110
  • 9
  • 98
  • 181
Tom B.
  • 21
  • 3

2 Answers2

3

Because it can get to the first answer checking door(X,Y) and not yet checking door(Y,X) and had left a choicepoint. When you asked it to look for more, it looked at door(Y,X) and found no more answers. It can't get to the second query result without checking both, so there's no more to check.

TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87
2

Prolog programs are linear, top-down; and Prolog execution is also linear, top-down.

The first query checks the first connect/2 clause, which succeeds. So it stops temporarily, reports the finding, and asks the user whether to continue. Prolog does not know in advance whether the search will succeed any further or not. If the user presses ;, the search continues and discovers no more solutions, reporting false.

The second query goes through the same two clauses of the connect/2 predicate, but this time the first clause does not match, so there is no solution found through that clause. The search thus continues immediately with the second clause.

When that produces its result successfully, Prolog knows that it has just tried the last clause in the connect/2 definition. It knows that there's no more further search possible. So it reports its findings and stops right away.

Hypothetically speaking, we could imagine an implementation employing speculative evaluation. Then it could sometimes detect that the search is exhausted, spending some resources on some background evaluation in advance. Your implementation most likely does not do that.

Will Ness
  • 70,110
  • 9
  • 98
  • 181