|- Up -||Next >>|
Prolog contains an important predicate for comparing terms, namely
==. This tests whether two terms are identical. It does not instantiate variables, thus it is not the same as the unification predicate
Let's look at some examples:
?= a == a.
?- a == b.
?- a == 'a'.
These answers Prolog gives here should be obvious, though pay attention to the last one. It tells us that, as far as Prolog is concerned,
'a' are literally the same object.
Now let's look at examples involving variables, and explicitly compare
== with the unification predicate
X = _2808
Y = _2808
In these queries,
Y are uninstantiated variables; we haven't given them any value. Thus the first answer is correct:
Y are not identical objects, so the
== test fails. On the other hand, the use of
= succeeds, for
Y can be unified.
Let's now look at queries involving instantiated variables:
?- a=X, a==X.
X = a
The first conjunct,
a. Thus when
a==X is evaluated, the left-hand side and right-hand sides are exactly the same Prolog object, and
A similar thing happens in the following query:
?- X=Y, X==Y.
X = _4500
Y = _4500
X=Y first unifies the variables
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
== are very different, nonetheless there is an important relation between them. Namely this:
== can be viewed as a stronger test for equality between terms than
=. That is, if
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 precisely in those case where
== fails. That is, it succeeds whenever two terms are not identical, and fails otherwise. For example:
?- a \== a.
a \== b.
a \== 'a'.
These should be clear; they are simply the opposite of the answers we got above when we used
==. Now consider:
X = _3719
Why this response? Well, we know from above that the query
X==a fails (recall the way
== treats uninstantiated variables). Thus
X\==a should succeed, and it does.
X = _798
Y = _799
Again, we know from above that the query
X==Y fails, thus
|- Up -||Next >>|