I am studying on Ivan Bratko book: “Programming for artificial intelligence”
Now I am studying the operators and I have some doubts about it, on the book I can read the following thing:
So the precedence of the operators decides what is the correct interpretation of expressions. For example, the expression a + b*c can be, in principle, understood either as:
1. +(a, *(b,c))
or as:
2. *(+(a,b), c)
And now I havde the first doubt: “what it means this thing? it seems me very strage because these two expressions give different three and different result !!!
For example if I have: a=2
, b=3
, c=4
The result of the first one is 14 and the result of the second one is 20 so there are different: different thress means different order of operator execution that means different result !!!
So I think that (using the usual priority of arithmetic operator: execute first the multiplications and after the sums) the correct expression is the first one and the second one is wrong.
Is it correct?
Continuing to read the book I can read also:
The general rule is that operator with the highest precedence is the principal functor of the term. If expression containing + and * are to be understood according to our normal convention, then + have a higher precedence then * operator
and now I have the second doubt: as I said, in normal convention of arithmetic I execute first the multiplications and after the sums,so in my opinion is the * operator that have the precedence and not +
What I am missing about it? Why on the book say that +
has higher precedence then *
?
2
Answers
“The principal functor of the term” means the last operation to be executed, or the outermost one in prefix notation. This definition is the inverse of yours, thus the contradiction.
It says that without precedence, those are 2 possible ways to interpret the expression (and different way of parsing the expression will give different result). You only know to group
a + (b * c)
when you know that*
should be executed before+
. (I avoid explaining with precedence here, since it is confusing as pointed out below).+
and*
are just symbols, and it just happens that they are used as operator with some defined precedence. Generally speaking, you can define anything to be an operator, and give it a precedence.The definition of precedence in English is “The condition of being considered more important than someone or something else; priority in importance, order, or rank”. As long as something has to happen before some other thing, we have a precedence.
In C, operator precedence is the order of binding in an expression. Higher precedence operator in C will get executed before lower precedence operators.
In Prolog, the precedence is the order of getting the functor, which is the reverse of the case of C operator’s order of binding. Higher precedence operator will appear earlier when we analyze the expression with
=..
.