- 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.
yes
?- a == b.
no
?- a == 'a'.
yes
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
and 'a'
are literally 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 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 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 precisely in those case 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 should be clear; 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 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 X\==Y
succeeds
- Up - | Next >> |