|–||unary minus||Try the query |
Except in the context of an arithmetic comparison operator, arithmetic
expressions need to be explicitly evaluated in Prolog, using
is built-in predicate.
Mostly one uses these operators in a goal more like this:
X is Y + 2where
Yis a variable already bound to a numeric value, or perhaps a arithmetic comparison goal like this:
X > Y * ZHere's another example: a rule to tell if a (whole) number is odd:
odd(Num) :- 1 is Num mod 2.Another way to do this one is to use
odd(Num) :- Num mod 2 =:= 1.If you wanted to be more cautious, you could first check that
Numis in fact a whole number:
odd(Num) :- integer(Num), 1 is Num mod 2.
As usual in digital computations, with fractional numbers, it is
necessary to be careful with
approximation issues. Thus the final example in the table above,
1.21 is 1.1 ** 2. actually fails when typed into Prolog
as a query. This is because 1.1 ** 2, as represented in computers,
actually comes out to be something like 1.210000000001. See the section
on comparison operators for a solution to
Note that SWI Prolog does some apparently strange stuff in the domain of arithmetic (dialogue below done with SWI-Prolog Version 5.6.58):
?- X is [a]. X = 97. ?- X is [a] + [b]. X = 195. ?- X is sqrt(23456). X = 153.154. ?- X is sqrt(). X = 153.154. ?- X is sqrt(123456789). X = 11111.1. ?- X is sqrt(). X = 13.3791.The ASCII code for a is 97, which sort of explains the first two query outcomes. The last pair of queries are particularly strange. It is best to avoid relying on this sort of thing, and stick to standard arithmetical notation. Avoid strange tricks: code should be comprehensible.
See also comparison operators, built-in functions.