2.3 Arithmetic in Prolog

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 (where Expression is some arithmetical expression)

X is Expression8

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.

The built-in predicate display/1 can be used to reveal the ‘real’ constitution of expressions containing operators. For example,

?-  display(X is 10 + 5 * 6 / 3).  
is(_G292, +(10, /(*(5, 6), 3)))

shows that is/2 is the principal functor, then +, then / and so on. This is very handy if you are unsure about the effects of your operator declarations.

2.3.1 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:9

length([H|T], N):-  
   length(T, N1),  
   N is N1 + 1.

2.3.2 Exercises

Exercise 10Define predicate square/2 that takes a number as its first argument and returns the square of that number as its second argument. (No recursion in this one.)

Exercise 11Define a predicate power/3 that takes numbers as its first two arguments P and N and returns as the value of its third argument a number which is N to the power of P. E.g.

?- power(3,2,P).  
 
P = 8  
 
yes

Note that this requires a recursive rule and the use of arithmetic.