gpt4 book ai didi

ruby - 一元减号是否应该对数字文字具有更高的优先级?

转载 作者:数据小太阳 更新时间:2023-10-29 07:54:48 25 4
gpt4 key购买 nike

当涉及数字文字时,一元减号似乎具有特殊的优先级。这是记录在案的行为吗?

我见过的优先级表(例如 here)甚至没有提到点(方法调用)运算符。

在 ruby​​ 2.3.6 上测试:

puts "=== literal integer ==="
# `-` has higher precedence than `.`
p( -1.abs ) # => 1
p( -(1.abs) ) # => -1 (previous line should match this if `.` had higher precedence)

puts "=== literal float ==="
# again `-` has higher precedence than `.`
p( -1.2.abs ) # => 1.2
p( -(1.2.abs) ) # => -1.2 (previous line should match this if `.` had higher precedence)

puts "=== integer in a variable ==="
(1).tap do |i|
# `.` has higher precedence
p( -i.abs ) # -1
p( (-i).abs ) # 1 (previous line should match this if `-` had higher precedence)
end

puts "=== float in a variable ==="
(1.2).tap do |i|
# `.` has higher precedence
p( -i.abs ) # -1.2
p( (-i).abs ) # 1.2 (previous line should match this if `-` had higher precedence)
end

puts "=== literal string ==="
'a'.frozen? == false or raise "frozen_string_literal must be disabled"

# Note that unary minus on Strings returns a frozen copy if the string wasn't already frozen
# `.` has higher precedence (differs from numeric precedence)
p( (-'a'.succ).frozen? ) # true
p( ((-'a').succ).frozen? ) # false (previous line should match this if `-` had higher precedence)

最佳答案

原因是在字面量的情况下,前面的-不是一元运算符,而是字面量语法的一部分。

但是,- 运算符本身的优先级低于方法调用。鉴于字符串没有 -'string' 文字语法,无论字符串是否为文字,此规则始终适用。

class Integer
def -@
puts 'Called'
end
end

class String
def -@
puts 'Called'
end
end

-1 # nothing, the - wasn't an unary operation, but part of the number construction
x = 1
-x # Called

-'a' # Called
a = 'a'
-a # Called

另一个有趣的事情是,如果你在数字和 - 之间放置一个空格,- 就不再是文字语法的一部分。

- 1 # Called

语义解释如下:

  • “负数”这样的东西。它应该有文字语法(就像任何正数一样)是有道理的。最直观的语法是 -1
  • 我们仍然希望能够对文字正数调用一元运算符。最直观(且易于实现)的方法不是让解析器 super 花哨地忽略负数的文字语法中的任何随机数量的空格。因此,为什么 - 1 说明 “将一元减号应用于数字(正)一”
  • 不存在“字符串负数‘a’”这样的东西。这就是为什么 -'a' 表示 “将一元减号应用于字符串 'a'”

关于ruby - 一元减号是否应该对数字文字具有更高的优先级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51750938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com