I want to express a transitive relationship. If A references B and B references C then A references C. I have this:
proj(A).
proj(B).
proj(C).
ref(A,B).
ref(B,C).
When I query using proj(A)
I obtain:
[46] ?-proj(A).
A = _639
What does "_639" mean? I expected a yes or no and got that strangeness. I need to add a rule to say:
ref(A,C).
and get YES. Ideally, if possible, I would like to show how this relationship came about: (A => B => C).
The
_639
is an uninstantiated, anonymous variable. Your "facts" have variables rather than atoms. For example:So if I query:
You need atoms:
Which results in the query:
If you have:
Then, the simplest way in Prolog to express a transitive property is by declaring a rule (or what's known as a predicate in Prolog):
This says that,
ref(A,C)
is true ifref(A,B)
is true, ANDref(B,C)
is true.. Running the query:Or:
So it sounds logical but has an issue: you can get into a loop due to the self-reference. A simple way around that is to make the rule name different than the fact:
Now if I query:
Etc.
There are still cases where this could have termination issues, however, if the facts contain reflexive or commutative relationships. For example:
In this case, a query to
refx(a, b)
yields:As @lambda.xy.x points out, this could be resolved by tracking where we've been and avoiding repeat "visits":
Now we terminate with
refx(a,b)
and succeed once:And
refx(X, Y)
produces all of the solutions (albeit, some repeats due to succeeding more than once):