Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - Creating Custom Operators



Prolog provides a powerful option to create a custom operator using op/3 predicate.

Syntax

op(Precedence, Type, OperatorName).

Where −

  • Precedence − it is an integer from 1 to 1200. Higher the value, lower the precedence. For example, :- is having low precedence like 1200 while arithmetic operator have higher Precedence.

  • Type − it is an atom to indicate the operator's type and associativity as shown below −

    • xfx, xfy, yfx − infix type

    • fx, fy − prefix type

    • xf, yf − postfix type

  • OperatorName − Name of the operator for example, is_friend_of.

Example - Creating a Custom Operator

Let's create a operator is_friend_of using oppredicate.

:- op(800, xfx, is_friend_of).

Where −

  • 800 − a medium level Precedence

  • xfx − non-associative infix operator

  • is_friend_of − name of the operator

Let's now create facts using our custom operator.

john is_friend_of mary.
susan is_friend_of peter.

Now we can make queries as shown below −

?- john is_friend_of X.
X = mary

?- Who is_friend_of peter.
Who = susan.

Complete Example

Following is the complete example of creating and using custom operator.

Program(custom.pl)

:- op(800, xfx, is_friend_of).
john is_friend_of mary.
susan is_friend_of peter.

Output

| ?- consult('D:/TP Prolog/Sample Codes/custom.pl').
compiling D:/TP Prolog/Sample Codes/custom.pl for byte code...
D:/TP Prolog/Sample Codes/custom.pl compiled, 2 lines read - 435 bytes written, 4 ms

yes
| ?- john is_friend_of X.

X = mary

yes
| ?- Who is_friend_of peter.

Who = susan

yes
| ?- 
Advertisements