Download Introduction to Prolog Programming
Transcript
Chapter 4 Operators In the chapter on arithmetic expressions we have already seen some operators. Several of the predicates associated with arithmetic operations are also predefined operators. This chapter explains how to define your own operators, which can then be used instead of normal predicates. 4.1 Precedence and Associativity Precedence. From mathematics and also from propositional logic you know that the precedence of an operator determines how an expression is supposed to be interpreted. For example, ∧ binds stronger than ∨, which is why the formula P ∨ Q ∧ R is interpreted as P ∨ (Q ∧ R), and not the other way round. In Prolog every operator is associated with an integer number (in SWI-Prolog between 0 and 1200) denoting its precedence. The lower the precedence number the stronger the operator is binding. The arithmetic operator *, for example, has a precedence of 400, + has a precedence of 500. This is why, when evaluating the term 2 + 3 * 5, Prolog will first compute the product of 3 and 5 and then add it to 2. The precedence of a term is defined as 0, unless its principal functor is an operator, in which case the precedence is the precedence of this operator. Examples: • The precedence of 3 + 5 is 500. • The precedence of 3 * 3 + 5 * 5 is also 500. • The precedence of sqrt(3 + 5) is 0. • The precedence of elephant is 0. • The precedence of (3 + 5) is 0. • The precedence of 3 * +(5, 6) is 400. 27