Step 1 of 5 · Reading · ~3 min
Learn
Unification, 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
Every variable on the right must already be bound, or you get an instantiation_error.
Operators
+,-,*,///— integer divisionmod/rem— two different remainders (see below)**and^— two different exponentiations (see below)abs/1,sign/1,max/2,min/2sqrt/1,sin/1,cos/1,log/1,exp/1truncate/1,round/1,floor/1,ceiling/1pi,e— constants
Two traps measured on this course's grader (GNU Prolog 1.4.5)
** is the floating-point power and ^ is the integer power. They do not print the same thing:
X is 2 ** 10. %% X = 1024.0 — a float
Y is 2 ^ 10. %% Y = 1024 — an integer
If a grader expects 1024 and you wrote **, you print 1024.0 and fail on a difference the source never shows you. / behaves the same way: 5 / 2 is 2.5, and even 4 / 2 is 2.0, never 2. Use // when you want an integer.
mod and rem agree on positive operands and disagree on negative ones — mod takes the sign of the divisor, rem takes the sign of the dividend:
X is 7 mod 3. %% X = 1
Y is -7 mod 3. %% Y = 2 — divisor's sign
Z is -7 rem 3. %% Z = -1 — dividend's sign
Comparison
=:=numerical equality (evaluates both sides)=\=numerical inequality<,>,=<,>=numerical compare
2 + 2 =:= 4. %% true
2 + 2 = 4. %% FAILS — `2+2` is a compound term, 4 is a number
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 number
Variables not yet bound: X is Y + 1 with Y unbound raises instantiation_error. Y needs a value before is can run.
Floats are binary: X is 0.1 + 0.2 gives 0.30000000000000004 here, exactly as it does in C, Python and JavaScript. Compare floats with a tolerance, never with =:=.
Constraint Logic Programming (preview)
Standard arithmetic only runs forwards — X + 2 =:= 5 with X unbound is an error, not an equation to solve. CLP(FD) turns it into one:
:- use_module(library(clpfd)).
X + 2 #= 5. %% X = 3 — works in reverse
That is a separate library, and a subject for the Intermediate course.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…