In this guide, we will discuss Operators in Prolog. In the following sections, we will see what are the different types of operators in Prolog. Types of the comparison operators and Arithmetic operators.
We will also see how these are different from any other high level language operators, how they are syntactically different, and how they are different in their work. Also we will see some practical demonstration to understand the usage of different operators.
Comparison Operators
Comparison operators are used to compare two equations or states. Following are different comparison operators −
Operator | Meaning |
---|---|
X > Y | X is greater than Y |
X < Y | X is less than Y |
X >= Y | X is greater than or equal to Y |
X =< Y | X is less than or equal to Y |
X =:= Y | the X and Y values are equal |
X =\= Y | the X and Y values are not equal |
You can see that the ‘=<’ operator, ‘=:=’ operator and ‘=\=’ operators are syntactically different from other languages. Let us see some practical demonstration to this.
Example
| ?- 1+2=:=2+1. yes | ?- 1+2=2+1. no | ?- 1+A=B+2. A = 2 B = 1 yes | ?- 5<10. yes | ?- 5>10. no | ?- 10=\=100. yes
Here we can see 1+2=:=2+1 is returning true, but 1+2=2+1 is returning false. This is because, in the first case it is checking whether the value of 1 + 2 is same as 2 + 1 or not, and the other one is checking whether two patterns ‘1+2’ and ‘2+1’ are same or not. As they are not same, it returns no (false). In the case of 1+A=B+2, A and B are two variables, and they are automatically assigned to some values that will match the pattern.
Arithmetic Operators in Prolog
Arithmetic operators are used to perform arithmetic operations. There are few different types of arithmetic operators as follows −
Operator | Meaning |
---|---|
+ | Addition |
– | Subtraction |
* | Multiplication |
/ | Division |
** | Power |
// | Integer Division |
mod | Modulus |
Let us see one practical code to understand the usage of these operators.
Program
calc :- X is 100 + 200,write('100 + 200 is '),write(X),nl, Y is 400 - 150,write('400 - 150 is '),write(Y),nl, Z is 10 * 300,write('10 * 300 is '),write(Z),nl, A is 100 / 30,write('100 / 30 is '),write(A),nl, B is 100 // 30,write('100 // 30 is '),write(B),nl, C is 100 ** 2,write('100 ** 2 is '),write(C),nl, D is 100 mod 30,write('100 mod 30 is '),write(D),nl.
Note − The nl is used to create new line.
Output
| ?- change_directory('D:/TP Prolog/Sample_Codes'). yes | ?- [op_arith]. compiling D:/TP Prolog/Sample_Codes/op_arith.pl for byte code... D:/TP Prolog/Sample_Codes/op_arith.pl compiled, 6 lines read - 2390 bytes written, 11 ms yes | ?- calc. 100 + 200 is 300 400 - 150 is 250 10 * 300 is 3000 100 / 30 is 3.3333333333333335 100 // 30 is 3 100 ** 2 is 10000.0 100 mod 30 is 10 yes | ?-
Next Topic : Click Here
Pingback: Prolog - Data Objects | Adglob Infosystem Pvt Ltd