Maurice Lombardi wrote:
Maurice Lombardi wrote:
Irfan Fazel wrote:
writeln(-2 pow 0); (* should be 1 *)
writeln(-2 pow 1);
writeln(-2 pow 2); writeln; (* should be 1 *)
Problem of relative priority between - and pow.
writeln(-2 pow 0,' ',(-2) pow 0);
gives
-1 1
IIRC priority of pow should be greater than binary - but smaller than unary - This would give the behaviour that everybody expects.
No this is stupid: -a pow 2 should be -(a pow 2) to give what everybody expects.
Only for a number -2 the - should take precedence.
This would seem quite inconsistent. If you replace the number 2 by, say, a constant a = 2, you get a different precedence!?
J. David Bryan wrote:
On 8 Sep 2001, at 10:44, Maurice Lombardi wrote:
What says the standard ?
The Extended Pascal standard, Section 6.8.1 "Expressions, General" says:
"Operator precedences shall be according to five classes of operators as follows. The operator 'not' shall have the highest precedence, followed by the exponentiating-operators, followed by the multiplying-operators, the adding-operators and signs, and finally, with the lowest precedence, the relational-operators. Sequences of two or more operators of the same precedence shall be left associative."
Section 6.8.3.1, "Operators, General" defines the types of operators mentioned above:
exponentiating-operator = "**" | "pow"
multiplying-operator = "*" | "/" | "div" | "mod" | "and" | "and_then"
adding-operator = "+" | "-" | "><" | "or" | "or_else"
relational-operator = "=" | "<>" | "<" | ">" | "<=" | ">=" | "in"
So that means that unary minus has the same precedence as binary minus, which is lower than that of "pow". So:
-2 pow 2
is evaluated as:
-(2 pow 2)
and so equals -4. GPC is correct.
As an aside, these rules are a bit odd, in that:
a = b and c = d
is evaluated as:
a = (b and c) = d
rather than as the more likely intended:
(a = b) and (c = d)
I consider this one of the real design mistakes of Pascal (of course, we can't do anything about it now).
da Silva, Joe wrote:
FWIW: I'm not good on the jargon, but is "-2" really a unary "-" and a number (2), or is "-2" a number in itself (ie. the sign is not an operator)?
6.8.1 defines a "primary" in an expression to be (among other things) an unsigned constant, and allows a sign only in "simple_expression" (on the same level as adding operators).
This is what Maurice suggested in his second posting, and is the natural/intuitive interpretation of "-2".
In mathematics, it's not: -2^2 = -4 (just as in Pascal).
(In non-mathematic usage, you rarely deal with situation like powers of negative numbers, where the difference actually matters.)
Frank