Issue #7331 has been updated by alexeymuranov (Alexey Muranov).


After some thinking, i want to add my last word on this :).  I have not seen any "official" rule on parsing "- 2 * 3".  However, i'll try to explain my reasons for believing that "- (2 * 3)" should be the "right" parsing.

In my opinion, it is not a proper way to teach a second-grade child to evaluate  "- 2 * 3" by saying:
Hey! (or Yo!) Multiplication is associative and distributes over addition and subtraction, whether you compute "- 2 * 3" as "- (2 * 3)", as "(-2) * 3" or as "((-1)*2)*3" it will be all the same!

Because if i do, they may remain wondering what  "- 2 * 3" *means* and *how* to *evaluate* it.  So, i would simply say that the minus in front stands for "0 -", and the evaluation rules are the usual ones: first multiplications and divisions from left to right, then additions and subtractions from left to right. Which gives

- 2 * 3 = 0 - (2 * 3) = - (2 * 3).

Returning back to parsing expression in programming languages, the reason to parse "2 * - 3" as "2 * (- 3)" is not the operator precedence, but the fact that this expression is "invalid" as written, and fortunately, as "-" can be a unary prefix, but "*" cannot be a unary suffix, there exists a unique way to make this expression valid: add parentheses around "- 3".

Just to be sure that my opinion on parsing arithmetic unary minus is not a complete non-sense, i asked two colleagues across the hall about their opinions.  First they said that in "- 2 * 3" parentheses do not matter, and i can put them any way i like. So i started doubting if my opinion is not a complete nonsense.  However then i changed my question by asking how to teach a child to compute, and how to parse an expression in a programming language, and explained my point of view, and they both agreed completely.  (But maybe Marcus would be able to convince them otherwise.)

----------------------------------------
Bug #7331: Set the precedence of unary `-` equal to the precedence `-`, same for `+`
https://bugs.ruby-lang.org/issues/7331#change-37234

Author: alexeymuranov (Alexey Muranov)
Status: Rejected
Priority: Normal
Assignee: 
Category: core
Target version: 
ruby -v: 1.9.3


=begin
I will not be surprised if this proposal is rejected, because the compatibility would be a mess, but i feel i need to start a discussion.  This continues the discussion in #7328.

To the best of my knowledge, in mathematics the unary minus has the same precedence as the binary one.  However, in the expression

  - a * b

Ruby computes first (({-a})), and then the product.  This means that if i want (for whatever reason) to compute the expression in the natural order, i have to put the parentheses:

  - (a * b)

which looks very strange to me.  I would consider this a bug.
=end



-- 
http://bugs.ruby-lang.org/