Thursday 14 February 2019

Prolog: Arithmetic Operators


Prolog provides ‘is’ keyword to evaluate arithmetic expressions.

Syntax
X is <Some Arithmetic Expression>

1 ?- X is 2 + 3.
X = 5.

2 ?- Y is 2 - 3.
Y = -1.

3 ?- Z is 2 * 3.
Z = 6.

4 ?- W is 2 / 3.
W = 0.6666666666666666.

You can use parenthesis, to avoid the problems with operators precedence and associativity.

5 ?- X1 is 2 * (3/ (4 * 2)).
X1 = 0.75.

Apart from the arithmetic operators, Prolog provided below comparison operators.

Operator
Example
Description
> 
X > Y
Return true, if X is greater than Y, else false
< 
X < Y
Return true, if X is less than Y, else false
>=
X >= Y
Return true, if X is greater than or equal to Y, else false
=<
X =< Y
Return true, if X is less than or equal to Y, else false


Note: Unlike other languages, less than or equal to is not written as <=, it is written as =< in prolog.

8 ?- 10 > 11.
false.

8 ?- 10 < 11.
true.

9 ?- 10 >= 11.
false.

10 ?- 10 =< 11.
true.


You can even combine multiple operations in one line.

11 ?- X is 2 + 10, Y is 100, X > Y.
false.



Previous                                                 Next                                                 Home

No comments:

Post a Comment