120 likes | 297 Views
PROLOG. OPERATORS. PROLOG OPERATORS. There are existing Prolog operators: +, -, *, .. We have the concept of precedence in Prolog, as well as the concept of associativity We can design our own operator. PROLOG OPERATORS.
E N D
PROLOG OPERATORS
PROLOG OPERATORS • There are existing Prolog operators: • +, -, *, .. • We have the concept of precedence in Prolog, as well as the concept of associativity • We can design our own operator
PROLOG OPERATORS • There are 3 groups of Prolog operators (f represents the operator, x and y the arguments): • Infix operators: • type xfx, xfy, yfx • Prefix operators: • type fx and fy • Postfix operator: • type xf and yf
PROLOG OPERATORS • Why fx and fy? • x and y are different: • x represents an argument whose precedence level is strictly lower than the one of the operator f • y represents an argument whose precedence level is lower or equal to the one of the operator f
PROLOG OPERATORS • Example a – b – c • Generally understood as (a – b) – c • Not as a – (b –c) • To achieve that, - operator has to be defined as yfx
PROLOG OPERATORS • Example a – b – c • Generally understood as (a – b) – c • Not as a – (b –c) • To achieve that, - operator has to be defined as yfx
PROLOG OPERATORS • Precedence levels • A variable such as a or b, has precedence 0 • The – operator has precedence 500 • An expression such as a – b has the same precedence level as the operator inside the expression, here 500
PROLOG OPERATORS • a – b – c • If interpreted as (a – b) – c • a – b has precedence 500 (same as -) • c has precedence 0 • If interpreted as a – (b –c) • a has precedence 0 • b – c has precedence 500 (same as -)
PROLOG OPERATORS • a – b – c • If interpreted as (a – b) – c • Precedence 500 – precedence 0 • If interpreted as a – (b – c) • Precedence 0 – precedence 500 • Interpreted as (a – b) – c requires – to be yfx • (precedence of x strictly lower that precedence of f)
PROLOG OPERATORS • Define our own operator • :- op(level, type, name of operator) • Level is between 1 and 1200 • Type: xf, yf, fx, fy, xfx, xfy, yfx • Examples: • :- op(600, xfx, has). • :- op(50, xfy, :).
PROLOG OPERATORS • + has precedence 500 • * has precedence 400 • The lower the level, the higher the precedence • X is 3 + 4 * 2. • X = 11
PROLOG OPERATORS • Example of new operator • 8 queens problem: • How to represent position on chessboard (A,B) row A, column B • Can define an operator called : • A:B will represent the board square (A,B) • :- op(50,xfy,:).