Testing Unifiability

Often, it is necessary to check whether or not a term has a particular value. If we know that the term will be bound to a number, we can use the evaluable predicates =:=/2 or = \  = /2, as explained earlier. For other values, it may often be cheaper, in the appropriate circumstances, to use the predicates ?=/2 or \  = /2. For example, consider a predicate p/2 that calls q/1 with its second argument if its first argument unifies with a, and r/1 otherwise. A na&̈#305;ve definition might be

p(a, X) :- !, q(X). 

p(Y, X) :- r(X).

However, the call to p/2 results in the (temporary) creation of a backtrack point. A solution that avoids this backtrack point creation is

p(Y, X) :- Y ?= a -> q(X) ; r(X).
Of course, if the argument order in p/2 could be reversed in this case, then data movement would be reduced even further (see above), and the code would be even more efficient:
p(X, Y) :- Y ?= a -> q(X) ; r(X).