Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 40 ยท Arithmetic and Control

Arithmetic and the is Operator

Learn how Prolog does arithmetic. Why X = 2+3 does not give 5, how is/2 evaluates expressions, the arithmetic operators and functions, and how to write recursive numeric predicates.

Prolog is a language of terms and unification, not of calculation. When you write 2 + 3, Prolog sees a compound term +(2, 3): a structure with the functor + and two arguments. It does not add anything until you explicitly ask for evaluation. That is the most surprising thing about arithmetic for newcomers, and once you understand it, the rest is straightforward.

This lesson covers the is/2 predicate, the arithmetic functions you can use on its right-hand side, the common error that comes from unbound variables, and the classic recursive patterns (factorial, sum, counting) that use numbers. The examples use SWI-Prolog conventions, the most widely used system.

Terms are not evaluated

Try these queries in any Prolog toplevel:

PROLOG
?- X = 2 + 3.
X = 2+3.

?- 5 = 2 + 3.
false.

The first query unifies X with the term 2+3; nothing is computed. The second fails because the integer 5 and the structure 2+3 are different terms. Unification only compares shapes.

To compute, use is/2:

PROLOG
?- X is 2 + 3.
X = 5.

The right-hand side of is is evaluated as an arithmetic expression. The result is then unified with the left-hand side. So 5 is 2 + 3 is true, and 6 is 2 + 3 is false.

Three ways to relate numbers

A = B Unify the terms. No arithmetic.
A is Expr Evaluate Expr, unify the result with A.
A =:= B Evaluate both sides, compare values.

Only is, =:=, <, > and friends do arithmetic.

1 / 2

Operators and functions

Inside an expression you can use these (SWI-Prolog names):

Expression Meaning
X + Y, X - Y, X * Y add, subtract, multiply
X / Y division; exact integer result when it divides evenly, otherwise a float
X // Y integer division, truncating toward zero
X mod Y modulo, result has the sign of Y
X rem Y remainder, result has the sign of X
X ^ Y, X ** Y power
abs(X), sign(X) absolute value, sign
min(X, Y), max(X, Y) smaller, larger
sqrt(X), sin(X), log(X), exp(X) floating-point functions
truncate(X), round(X), ceiling(X), floor(X) float to integer
gcd(X, Y) greatest common divisor
pi, e, random(N), cputime constants and special values
PROLOG
?- X is 7 // 2, Y is -7 // 2, Z is 7 mod 3, W is -7 mod 3.
X = 3, Y = -3, Z = 1, W = 2.

?- X is 7 / 2, Y is 8 / 2.
X = 3.5, Y = 4.

?- X is max(3, 9) + abs(-4).
X = 13.

Integers have unlimited size in SWI-Prolog, so X is 2 ^ 100 gives an exact 31-digit result. Use ^ when you want an integer power. Mixing in a float anywhere makes the result a float: X is 2.0 * 3 gives 6.0.

The instantiation error

Everything on the right of is must be known at the moment it runs:

PROLOG
?- Y is X + 1.
ERROR: Arguments are not sufficiently instantiated

This is not a failure; it is an error that aborts the query. The usual fix is to reorder your goals so that X gets a value first. This also means is is not reversible: you cannot ask "which X gives 6 when I add 1?" with 6 is X + 1. For that you need the constraint library from Constraint Logic Programming.

The next stand-in shows the difference between = and is. Prolog is not available on this site, so the code below is a small Python model that behaves like Prolog in these respects.

Python = versus is (a Python model)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Order of goals matters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Comparing numbers

The comparison operators evaluate both sides and compare the values. They never bind anything.

Operator Meaning
A =:= B equal values
A =\= B different values
A < B, A > B less, greater
A =< B, A >= B less or equal, greater or equal

Note =<, not <=. The arrow <= is not a comparison in Prolog; writing it is a common slip. Also keep =:= apart from == and =: 2 + 3 =:= 5 is true, 2 + 3 == 5 is false (the terms are not identical), and 2 + 3 = 5 is false (they do not unify). The next lesson covers term comparison in depth.

Recursive numeric predicates

Arithmetic and recursion go together. Factorial in its direct form:

PROLOG
factorial(0, 1).
factorial(N, F) :-
    N > 0,
    N1 is N - 1,
    factorial(N1, F1),
    F is N * F1.
PROLOG
?- factorial(5, F).
F = 120.

The guard N > 0 keeps the second clause from applying to 0 and prevents an endless descent into negative numbers if you backtrack. The multiplication happens after the recursive call returns, so each pending multiplication stays on the stack.

An accumulator version moves the work before the call and lets Prolog reuse the stack frame (last-call optimization):

PROLOG
factorial(N, F) :- factorial(N, 1, F).

factorial(0, Acc, Acc).
factorial(N, Acc, F) :-
    N > 0,
    Acc1 is Acc * N,
    N1 is N - 1,
    factorial(N1, Acc1, F).

The same idea gives sum, count and range predicates. SWI-Prolog also provides between/3 to generate integers, succ/2 for successor and predecessor, and plus/3:

PROLOG
?- between(1, 4, X).
X = 1 ;
X = 2 ;
X = 3 ;
X = 4.

?- succ(X, 5).
X = 4.

Because between/3 leaves choice points, it is the idiomatic way to write a loop with backtracking, as you will see in findall, bagof and setof.

Common mistakes

  • Using = where you meant is, and then wondering why the answer prints as 2+3.
  • Putting an unbound variable on the right of is. Compute its value earlier in the clause body.
  • Writing X is X + 1. A Prolog variable cannot change; once X is bound this compares X with X + 1 and fails. Use a new variable: X1 is X + 1.
  • Expecting is to run backwards. It is a one-way calculator.
  • Writing <= instead of =<.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the query X = 4 * 2. answer?

    = only unifies. X is bound to the compound term 4*2; nothing is evaluated.
  2. 2. Which goal makes Y equal to the double of a known X?

    is evaluates its right-hand side and unifies the result with the left-hand side.
  3. 3. What happens with ?- Z is W + 1. when W has no value?

    The expression cannot be evaluated, so you get the error 'Arguments are not sufficiently instantiated'.
  4. 4. Which operator means 'less than or equal'?

    Prolog writes it =< so that <= stays free for use as an ordinary symbol.

Summary

  • = unifies terms; it never calculates. X is Expr evaluates Expr and unifies the result.
  • Everything on the right of is must already have a value, or you get an instantiation error.
  • Arithmetic comparisons (=:=, =\=, <, >, =<, >=) evaluate both sides and bind nothing.
  • Variables never change value, so loops are recursion with new variables, often with an accumulator.
  • between/3 and succ/2 are handy generators and converters for integers.

Next: Comparing and Ordering Terms