Why does Ruby `**` operator have higher precedence than unary `-`?

﹥>﹥吖頭↗ 提交于 2019-12-23 18:55:18

问题


This leads to the situation like:

-1 ** 0.5 #=> -1

Only parenthesis remedies it:

(-1) ** 0.5 #=> 6.123031769111886e-17+1.0i

which is less favorable then expected 1.i, but basically acceptable. Before I go to Ruby bugs to complain, I would like to know whether there is perhaps some reason for this to be so?


回答1:


Many languages define their operator precedence tables by modeling after mathematics' order of operations. In math, exponentiation does have higher precedence than multiplication, and unary negation is a multiplication, after all.

From matz in a reply to "the sign of a number is omitted when squaring it":

People with mathematical background demands precedence for ** being higher than that of unary minus. That's the reason.




回答2:


Yes, ** has a higher precedence in Ruby.

Unlike some languages, - is not lex'ed as part of the number literal and is thus just (and universally) the unary - (aka -@). That is, both -x and -1 parse the unary -@ as an operator applied to the result of the expression.



来源:https://stackoverflow.com/questions/13329083/why-does-ruby-operator-have-higher-precedence-than-unary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!