Skip to content
Arithmetic and is/2
step 1/5

Reading — step 1 of 5

Learn

~2 min readUnification, I/O, Arithmetic

Prolog separates structural matching (=) from arithmetic evaluation (is).

is/2 evaluates the right side

X is 2 + 3.       %% X = 5
Y is 5 * (2 + 3). %% Y = 25
Z is sqrt(16).    %% Z = 4.0

All variables on the right MUST be bound, or you get an instantiation_error.

Operators

  • +, -, *, /
  • // — integer division
  • mod / rem — modulo / remainder
  • ** or ^ — exponent
  • abs/1, sign/1, max/2, min/2
  • sqrt/1, sin/1, cos/1, log/1, exp/1
  • truncate/1, round/1, floor/1, ceiling/1
  • pi, e — constants

Comparison

  • =:= numerical equality (evaluates both sides)
  • =\= numerical NOT equal
  • <, >, =<, >= numerical compare
2 + 2 =:= 4.       %% true
2 + 2 == 4.        %% false — "2+2" is a different term from 4

Arithmetic recursion

%% gcd via Euclid
gcd(A, 0, A) :- A > 0.
gcd(A, B, G) :-
    B > 0,
    R is A mod B,
    gcd(B, R, G).

Common pitfalls

Forgetting is:

bad(N, R) :- R = N + 1.    %% R is the term "N + 1", NOT the value
good(N, R) :- R is N + 1.   %% R is the integer

Variables not yet bound:

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

Y needs a value before is works.

Mixed types:

X is 5 / 2.       %% X = 2.5 (float)
Y is 5 // 2.      %% Y = 2 (integer division)

Constraint Logic Programming (preview)

Standard Prolog can't run arithmetic in reverse:

X + 2 =:= 5.       %% ERROR — X not instantiated

CLP(FD) (constraint logic programming over finite domains) lets you write:

:- use_module(library(clpfd)).
X + 2 #= 5.        %% X = 3 — works in reverse

That's a separate library — see Intermediate course.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…