How to make a right-associative infix operator?

大兔子大兔子 提交于 2019-11-26 20:07:53

问题


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

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?


回答1:


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 >>:.

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


来源:https://stackoverflow.com/questions/15384744/how-to-make-a-right-associative-infix-operator

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