Prolog is not the programming language of choice for carrying out heavy-duty
mathematics. It does, however, provide arithmetical capabilities. The pattern
for evaluating arithmetic expressions is
X is Expression[5]
The variable X will be instantiated to the value of
Expression. For example,
| ?- X is 10 + 5. X = 15 ? yes
?- X is 10 - 5.
X = 5 yes
?- X is 10 * 5.
X = 50 yes
?- X is 10 / 5.
X = 2 yes
?- X is 10 + 5 * 6 / 3.
X = 20 yes
It
is important to note that Expression is not evaluated by itself. You
have to supply a variable (followed by the infix operator is/2) to
collect a result.
Other pre-defined Prolog arithmetic infix operators are
> |
greater than |
< |
less than |
>= |
greater than or equal to |
=< |
less than or equal to |
Later in the course we will use op/3 to define operators of our own,
to make programs easier to read. Here we will return to the topic of defining
recursive rules, with the addition of arithmetic.
length/2
It is often useful to be able to calculate (or check) the length of a list.
With arithmetic operators this is something that we can now do. The base is the
empty list, which is obviously of length 0. This give us the Prolog clause:
length([ ], 0).
The recursion simply requires that we add 1 for each item on the list:
length([H|T], N):- length(T, N1), N is N1 + 1.
[5] Remember that the equals sign is used in Prolog for unification, not arithmetic.