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.
?- a == a. yes ?- a == b. no ?- a == 'a'. yes
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 = .
?- X==Y. no ?- X=Y. X = _2808 Y = _2808 yes
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:
?- a=X, a==X.
X = a
yes
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:
?- X=Y, X==Y.
X = _4500
Y = _4500
yes
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:
?- a \== a. no ?- a \== b. yes ?- a \== 'a'. no
These answers should be understandable: they are simply the opposite of the answers we got above when we used == . Now consider:
?- X \== a.
X = _3719
yes
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.
Similarly:
?- X \== Y.
X = _798
Y = _799
yes
Again, we know from above that the query X==Y fails, thus the query X\==Y succeeds.