Prolog - Airthmetic Operators
Airthmetic Operators are for various arithmetic operations in Prolog. Following is the list of arithmetic operators −
| Operator | Meaning | Example Usage | Result |
|---|---|---|---|
| + | Returns the sum of two numbers. | X is 5 + 2. | X = 7 |
| - | Returns the subtraction of two numbers. Can act as unary minus as well. | X is 5 - 2. | X = 3 |
| * | Returns the multiplication of the numbers. | X is 5 * 2. | X = 10 |
| / | Returns the division of the numbers | X is 5 / 2. | X = 2.5 |
| // | Used for integer division. | X is 5 // 2. | X = 2 |
| mod | Used for modulo operation. | X is 5 mod 2. | X = 1 |
| ^ or ** | Used for exponentiation. | X is 5 ** 2. | X = 25.0 |
| abs/1 | Used to get absolute value. | X is abs(-2). | X = 2 |
| sqrt/1 | Used to get square root value. | X is sqrt(9). | X = 3.0 |
| float/1 | Used to convert number to float. | X is float(9). | X = 9.0 |
| round/1 | Used to round number to nearest integer. | X is round(9.3). | X = 9 |
| truncate/1 | Used to truncate number to integer. | X is truncate(9.3). | X = 9 |
| float_fractional_part/1 | Used to get fractional part of a float. | X is float_fractional_part(3.14) | X = 0.14000000000000012 |
| float_integer_part/1 | Used to get integer part of a float. | X = 3.0 | |
| min/2 | Used to get minimum of two numbers. | X is min(3,5) | X = 3 |
| max/2 | Used to get maximum of two numbers. | X is max(3,5) | X = 5 |
| pi | Used to get constant value of pi. | X is pi. | X = 3.1415926535897931 |
| is | Used to evaluate the arithmetic expression and unifies the result. | X is 5 + 2. | X = 7 |
is/2 predicate
is operator is used to evaluate the arithmetic expression and in Prolog, arithmetic expressions are not automatically evaluated.
Example
| ?- X is 5 + 2. X = 7 yes | ?- Y is 20/5. Y = 4.0 yes | ?- Z is (3 + 5) * 2. Z = 16 yes | ?-
If a variable is present in the arithmetic expression then it should be instantiated to a number before being evaluated using is operator otherwise prolog will report error.
| ?- A is B + 2. uncaught exception: error(instantiation_error,(is)/2)
Divison by default returns a float. In case of integer based division, we can use // operator as shown below −
| ?- C is 20//5. C = 4 yes | ?-
Advertisements