Prolog provides commands for comparing terms. The criteria for deciding the order of terms is as follows:
- All uninstantiated variables are less than all decimal numbers; all decimal numbers are less than all whole numbers; all whole numbers are less than all atoms; all atoms are less than all structures (including lists).
- Comparison of two integer or two decimal numbers is done numerically (the term with the larger numeric value is considered the greatest).
- Comparison of two atoms is done by comparing the text values they represent lexicographically.
- One structure is less than another if it has a lower arity (number of arguments). If two structures have the same arity then they are ordered by comparing their functors (names) lexicographically. If two structures have the same arity and functor then they are ordered by comparing their arguments in order. The first corresponding arguments that differ determines the order of the two structures.
The Prolog term comparison operators are: =
, ==
, @<
, @>
, @>=
and @=<
.
Prolog also has numeric comparison operators which specifically deal with numerical comparison.
Examples
Examples of comparing a uninstantiated variable to a whole number.
?- X @< 2.
X = UNINSTANTIATED VARIABLE
yes
?- 2 @< X.
no
?- X @=< 2.
X = UNINSTANTIATED VARIABLE
yes
?- 2 @=< X.
no
?- X @> 2.
no
?- 2 @> X.
X = UNINSTANTIATED VARIABLE
yes
?- X @>= 2.
no
?- 2 @>= X.
X = UNINSTANTIATED VARIABLE
yes
Examples of comparing a uninstantiated variable to an atom.
?- X @< atom.
X = UNINSTANTIATED VARIABLE
yes
?- atom @< X.
no
?- X @=< atom.
X = UNINSTANTIATED VARIABLE
yes
?- atom @=< X.
no
?- X @> atom.
no
?- atom @> X.
X = UNINSTANTIATED VARIABLE
yes
?- X @>= atom.
no
?- atom @>= X.
X = UNINSTANTIATED VARIABLE
yes
Examples of comparing a uninstantiated variable to a structure.
?- X @< structure(a,b,c).
X = UNINSTANTIATED VARIABLE
yes
?- structure(a,b,c) @< X.
no
?- X @=< structure(a,b,c).
X = UNINSTANTIATED VARIABLE
yes
?- structure(a,b,c) @=< X.
no
?- X @> structure(a,b,c).
no
?- structure(a,b,c) @> X.
X = UNINSTANTIATED VARIABLE
yes
?- X @>= structure(a,b,c).
no
?- structure(a,b,c) @>= X.
X = UNINSTANTIATED VARIABLE
yes