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)
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)
:
path/2
fails because it cannot unify X
with a
and c
at the same timeX
gets unified with a
and Y
with c
, then it calls edge(a, Z)
. edge(a,b)
, Z
gets unified with b
. Then it tries to prove path(b, c)
path/2
fails again because it cannot unify X
with b
and c
at the same timeX
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)
X
with c
and there are no further goals.