next up previous
Next: length/2 Up: Pure Prolog Previous: Associativity

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 Expression[*]
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(_45,+(10,/(*(5,6),3)))
true ?
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.

Subsections
next up previous
Next: length/2 Up: Pure Prolog Previous: Associativity
Steve Harlow 2001-11-26