为什么不同的运算符有不同的结合性?

发布于 2024-09-28 01:14:51 字数 403 浏览 5 评论 0原文

我已经转到 Ruby 编程语言,它让我思考运算符结合性。顺便说一句,这不是一个 Ruby 问题 - 它适用于所有语言。

我知道操作员必须关联一种方式或另一种方式,并且我可以理解为什么在某些情况下一种方式比另一种方式更好,但我很难看到更大的图景。语言设计者是否使用一些标准来决定什么应该从左到右,什么应该从右到左?是否在某些情况下,它比其他方式“有意义”,而在其他情况下,这只是一个任意决定?还是这一切的背后有某种宏伟的设计?

I've got to the section on operators in The Ruby Programming Language, and it's made me think about operator associativity. This isn't a Ruby question by the way - it applies to all languages.

I know that operators have to associate one way or the other, and I can see why in some cases one way would be preferable to the other, but I'm struggling to see the bigger picture. Are there some criteria that language designers use to decide what should be left-to-right and what should be right-to-left? Are there some cases where it "just makes sense" for it to be one way over the others, and other cases where it's just an arbitrary decision? Or is there some grand design behind all of this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

呆° 2024-10-05 01:14:51

通常情况下,语法是“自然的”:

  • 考虑x - y + z。您希望它是从左到右,这样您就得到 (x - y) + z 而不是 x - (y + z)
  • 考虑a = b = c。您希望它是从右到左的,以便得到 a = (b = c),而不是 (a = b) = c

我想不出一个例子来说明这个选择似乎是“任意”做出的。

免责声明:我不懂 Ruby,所以上面的示例基于 C 语法。但我确信同样的原则也适用于 Ruby。

Typically it's so the syntax is "natural":

  • Consider x - y + z. You want that to be left-to-right, so that you get (x - y) + z rather than x - (y + z).
  • Consider a = b = c. You want that to be right-to-left, so that you get a = (b = c), rather than (a = b) = c.

I can't think of an example of where the choice appears to have been made "arbitrarily".

Disclaimer: I don't know Ruby, so my examples above are based on C syntax. But I'm sure the same principles apply in Ruby.

旧夏天 2024-10-05 01:14:51

想象一下用括号写一两个世纪的所有内容。
您将了解哪个运算符最有可能首先将其值绑定在一起,以及哪个运算符最后绑定在一起。
如果您可以定义这些运算符的结合性,那么您希望以一种最小化括号的方式来定义它,同时以易于阅读的术语编写公式。即(*)在(+)之前,和(-)应该是左关联的。

顺便说一句,左/右关联与左/右递归的含义相同。关联这个词是数学角度的,递归这个词是算法的。 (参见“end-recursive”,看看你在哪里写了最多的括号。)

Imagine to write everything with brackets for a century or two.
You will have the experience about which operator will most likely bind its values together first, and which operator last.
If you can define the associativity of those operators, then you want to define it in a way to minimize the brackets while writing the formulas in easy-to-read terms. I.e. (*) before (+), and (-) should be left-associative.

By the way, Left/Right-Associative means the same as Left/Right-Recursive. The word associative is the mathematical perspective, recursive the algorihmic. (see "end-recursive", and look at where you write the most brackets.)

〗斷ホ乔殘χμё〖 2024-10-05 01:14:51

计算机科学中的大多数算子关联性都是直接从数学中切取的。特别是符号逻辑和代数。

Most of operator associativities in comp sci is nicked directly from maths. Specifically symbolic logic and algebra.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文