如何制作右结合中缀运算符? [英] How to make a right-associative infix operator?

查看:62
本文介绍了如何制作右结合中缀运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关联操作>>.问题在于它的成本线性取决于其左操作数的大小.所以一个表达式由一系列 n>>> 应用组成,比如

I have an associative operation >>. The problem is that its cost linearly depends on the size of its left operand. So an expression formed by a sequence of n applications of >> like

a >> a >> a >> a >> a >> ... >> a

n 而言,它具有二次成本,因为默认情况下中缀运算符是 左结合.如何使其右结合,以使这样的表达式的成本在 n 方面保持线性?

it has quadratic cost in terms of n, because by default infix operators are left-associative. How to make it right-associative so that the cost of such an expression is kept linear in terms of n?

推荐答案

我找到了解决方案.Scala 参考6.12.3 中缀操作部分说:

I found a solution. Scala reference says in section 6.12.3 Infix Operations:

运算符的结合性由运算符的最后一个字符决定.运营商以冒号:"结尾的是右结合.所有其他运算符都是左关联的.

The associativity of an operator is determined by the operator’s last character. Operators ending in a colon ‘:’ are right-associative. All other operators are left-associative.

因此,将 >> 重命名为 >>: 就足够了.

Therefore it was enough to rename >> to >>:.

我花了一些时间才意识到,虽然 a >>b 脱糖为 a.>(b)a >>: b 脱糖为 b.>>;:(a).所以我必须将 >>>: 定义为

It took me some time to realize that while a >> b is desugared into a.>>(b), a >>: b is desugared into b.>>:(a). So I had to define >>: as

def >>:(x: T): T = x >> this

这篇关于如何制作右结合中缀运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆