Prolog - Different and Not



Here we will define two predicates — different and not. The different predicate will check whether two given arguments are same or not. If they are same, it will return false, otherwise it will return true. The not predicate is used to negate some statement, which means, when a statement is true, then not(statement) will be false, otherwise if the statement is false, then not(statement) will be true.

So the term ‘different’ can be expressed in three different ways as given below −

  • X and Y are not literally the same

  • X and Y do not match

  • The values of arithmetic expression X and Y are not equal

So in Prolog, we will try to express the statements as follows −

  • If X and Y match, then different(X,Y) fails,

  • Otherwise different(X,Y) succeeds.

The respective prolog syntax will be as follows −

  • different(X, X) :- !, fail.

  • different(X, Y).

We can also express it using disjunctive clauses as given below −

  • different(X, Y) :- X = Y, !, fail ; true. % true is goal that always succeeds

Program

Following example shows how this can be done in prolog −

different(X, X) :- !, fail.
different(X, Y).

Output

| ?- [diff_rel].
compiling D:/TP Prolog/Sample_Codes/diff_rel.pl for byte code...
D:/TP Prolog/Sample_Codes/diff_rel.pl:2: warning: singleton variables [X,Y] for different/2
D:/TP Prolog/Sample_Codes/diff_rel.pl compiled, 2 lines read - 327 bytes written, 11 ms

yes
| ?- different(100,200).

yes
| ?- different(100,100).

no
| ?- different(abc,def).

yes
| ?- different(abc,abc).

no
| ?-

Let us see a program using the disjunctive clauses −

Program

different(X, Y) :- X = Y, !, fail ; true.

Output

| ?- [diff_rel].
compiling D:/TP Prolog/Sample_Codes/diff_rel.pl for byte code...
D:/TP Prolog/Sample_Codes/diff_rel.pl compiled, 0 lines read - 556 bytes written, 17 ms

yes
| ?- different(100,200).

yes
| ?- different(100,100).

no
| ?- different(abc,def).

yes
| ?- different(abc,abc).

no
| ?-

Not Relation in Prolog

The not relation is very much useful in different cases. In our traditional programming languages also, we use the logical not operation to negate some statement. So it means that when a statement is true, then not(statement) will be false, otherwise if the statement is false, then not(statement) will be true.

In prolog, we can define this as shown below −

not(P) :- P, !, fail ; true.

So if P is true, then cut and fail, this will return false, otherwise it will be true. Now let us see one simple code to understand this concept.

Program

not(P) :- P, !, fail ; true.

Output

| ?- [not_rel].
compiling D:/TP Prolog/Sample_Codes/not_rel.pl for byte code...
D:/TP Prolog/Sample_Codes/not_rel.pl compiled, 0 lines read - 630 bytes written, 17 ms

yes
| ?- not(true).

no
| ?- not(fail).

yes
| ?-
Advertisements