0
votes

Prolog newbie here. I have this program:

edge(a,b).
edge(b,c).

path(X,X).
path(X,Y):- edge(X,Z),path(Z,Y).

I can't understand why Prolog returns true to this query:

path(a,c)

1
Why do you expect the query to fail?Willem Van Onsem

1 Answers

0
votes

It returns true because the prolog engine can prove your query.

You can imagine the prolog engine doing this when you query path(a,c):

  • first clause of path/2 fails because it cannot unify X with a and c at the same time
  • so it enters the second clause where X gets unified with a and Y with c, then it calls edge(a, Z).
  • As there is a fact edge(a,b), Z gets unified with b. Then it tries to prove path(b, c)
  • The first clause for path/2 fails again because it cannot unify X with b and c at the same time
  • so it enters the second clause where X gets unified with b and Y with c, then it calls edge(b, Z). Note that this variables (X, Y, Z are not the same variables as in the first call to path). Then it tries to prove path(c, c)
  • Now the first clause for path/2 succeeds as it unifies X with c and there are no further goals.
  • The previous calls to path/2 also succeed because they were at the final goal in each clause.