isbuilt-in predicate is used in Prolog to force the evaluation of arithmetic expressions. If you just write something like
X = 2 + 4, the result is to bind
Xto the unevaluated term
2 + 4, not to
?- X = 2 + 4. X = 2+4
If instead you write
X is 2 + 4, Prolog arranges
for the second argument, the arithmetic expression
2 + 4,
to be evaluated (giving the result
6) before binding
the result to X.
?- X is 2 + 4. X = 6
It is only and always the second argument that is evaluated. This
can lead to some strange-looking bits of code, by mathematical
standards. For example,
mod is the remainder-after-division
operator, so in Prolog, to test whether a number
is even, we write
0 is N mod 2, rather than the
usual mathematical ordering: N mod 2 = 0.
What is the difference between
N = 1 and
N is 1? In final effect, nothing. However, with
N is 1, Prolog is being asked to do an extra step
to work out the value of 1 (which, not surprisingly, is 1).
Arguably, it is better to use
N = 1, since this does
not call for an unnecessary evaluation.
The message is: use
is only when you
need to evaluate an arithmetic expression.
Actually, you don't need to use
evaluate arithmetic expressions that are arguments to the arithmetic
>, >=, < =<, =:= (equal), and =\= (not equal),
all of which automatically evaluate their arguments.
Note the syntax of
Thus things like
X*Y is Z*W do not work, as
is an expression, not a variable - use either
0 is X*Y - Z*Wor
X*Y =:= Z*Winstead.
A common mistake, for people used to procedural programming
languages like C and Java, is to try to change the binding of a variable
by using an goal like
N is N + 1. This goal will
never succeed, as it requires
N to have the same value
N + 1, which is impossible. If you find yourself
wanting to do something like this, you could look at the code
factorial in the article on
Another common mistake is to try a goal involving
before the variable(s) on the right-hand side of the
has/have been instantiated. Prolog cannot evaluate an arithmetic
expression if it doesn't know the values of variables in the expression.
This is why the following example fails:
?- X is Y + 1, Y = 3. ERROR: is/2: Arguments are not sufficiently instantiatedCompare this with:
?- Y = 3, X is Y + 1. Y = 3, X = 4.