Matching: the built-in predicates =
and
\=
Prolog provides a built-in predicate which takes two arguments
and check whether they match. This predicate is
=/2
. How does Prolog answer to the following
queries? Then about it first, and then type it into Prolog to
check whether you are right.
?- =(harry,harry). ?- =(harry,'Harry'). ?- =(f(a,b),f(a(b))).
Prolog also allows you to use =
as an infix operator. So, instead of writing
=(harry,harry)
you can write harry = harry
.
Matching in Prolog is a destructive operation because variables get instantiated. So, the terms that are matched may be different after matching to what they were before matching. Here is a sequence of queries that illustrates this.
?- X = harry, Y = hermione. X = harry Y = hermione ; noMatching the variable
X
with harry
and the variable Y
(a different variable) with hermione
works and instantiates both variables.
?- X = harry, X = hermione. noAfter the first goal
X = harry
has been processed,
the variable is instantiated to
harry
. harry
does not match with
hermione
(different atoms), so that the second goal
fails.
The built-in predicate \=/2
works in the opposite
way: Arg1 \= Arg2
is true if
Arg1 = Arg2
fails, and vice
versa. (Note that not all Prolog implementations provide
\=/2
. SWI Prolog does, but Sicstus, for example,
doesn't.)
Try some queries involving =
and
\=
. For example,
?- s(np(pn(dobey)),vp(v(likes),np(pn(harry)))) = s(np(pn(dobey)),v(likes),np(pn(harry))). ?- s(X,vp(v(sings))) = s(np(pn(dobey)),Y). ?- s(X,vp(v(sings))) = s(np(pn(dobey)),vp(X)). ?- father(X) = X.