To Prolog a numerical expression is just a structure which can be
manipulated just like any other term. So the expression 2 + 3 * 4
can be "unpacked" like any other term. For example, the goal:
|?- 2+3*4 = X+Y.Unpacks
2+3*4
into subterms X
(instantiated to 2
)
and Y
(instantiated to 3*4
).
If you want to evaluate a numerical expression, such as
the one given above, then you must use the built in operator:
is
. This is an infix
operator which takes on its right side a numerical expression to be
evaluated and the result of evaluating this expression is the number
on its left side. For example, to find the result of evaluating the
expression 2+3*4
we give the goal:
|?- X is 2+3*4. X=14 yesWe don't have to put a variable on the left of the
is
operator. We
could use it to test that a particular number is the result of
evaluating a given numerical expression:
|?- 14 is 2+3*4. yesOnly certain special operators are allowed in evaluable expressions (i.e. terms which appear on the right side of
is
goals). These
include the normal arithmetic operators +
(addition), -
(subtraction), *
(multiplication) and /
(division).
Some dialects of Prolog also allow operators such as sin/1
,
cos/1
, etc.
Just to emphasise that numerical expressions can be picked up from the database and passed around like any other expression, only being evaluated when you want it to, consider the following program: We represent data expressions using the following two facts:
data(2). data(3*4).We then give a rule which will calculate the sum of any pair of data expressions contained in the database:
calc(N):- data(N1), data(N2), N is N1 + N2.We can then find the sums of all combinations of data expressions by giving the goal
calc(N)
and forcing backtracking for alternative
solutions using the `;'
operator:
| ?- calc(N). N=4 ; N=14 ; N=14 ; N=24 yes