9.1 Comparing Terms
Prolog contains an important predicate for comparing terms, namely the identity predicate ==/2 . As its name suggests, this tests whether two terms are identical. However ==/2 does not instantiate variables, thus it is not the same as the unification predicate =/2 . Let’s look at some examples.
The reason Prolog gives these answers should be clear, though pay attention to the last one. It tells us that, as far as Prolog is concerned, a and ’a’ are the same object.
Now let’s look at examples involving variables, and explicitly compare == with the unification predicate = .
In these queries, X and Y are uninstantiated variables; we haven’t given them any value. Thus the first answer is correct: X and Y are not identical objects, so the == test fails. On the other hand, the use of = succeeds, for X and Y can be unified.
Let’s now look at queries involving instantiated variables:
The first conjunct, a=X , binds X to a . Thus when a==X is evaluated, the left hand side and right hand sides are exactly the same Prolog object, and a==X succeeds.
A similar thing happens in the following query:
The conjunct X=Y first unifies the variables X and Y . Thus when the second conjunct X==Y is evaluated, the two variables are exactly the same Prolog object, and the second conjunct succeeds as well.
It should now be clear that = and == are different, nonetheless there is an important relation between them: == can be viewed as a stronger test for equality between terms than = . That is, if term1 and term are Prolog terms, and the query term1 == term2 succeeds, then the query term1 = term2 will succeed too.
Another predicate worth knowing about is \== . This predicate is defined so that it succeeds in precisely those cases where == fails. That is, it succeeds whenever two terms are not identical, and fails otherwise. For example:
These answers should be understandable: they are simply the opposite of the answers we got above when we used == . Now consider:
Why this response? Well, we know from above that the query X==a fails (recall the way == treats uninstantiated variables). Thus the query X\==a should succeed , and it does.
Again, we know from above that the query X==Y fails, thus the query X\==Y succeeds.