关于Scala List中xs reverse_::: ys与xs.reverse ::: ys的原理疑问
reverse_::: vs reverse ::: in Scala Lists Great question! Let's break this down clearly to resolve your confusion:
What is xs reverse_::: ys?
This is Scala's infix method call syntax in action. When you write xs reverse_::: ys, you're actually invoking the method reverse_::: directly on the list xs, passing ys as its single parameter — in other words, it's exactly equivalent to xs.reverse_:::(ys).
The reverse_::: method is optimized specifically for this use case: it reverses xs and concatenates ys to the end of that reversed list in one single operation, without creating an intermediate reversed list first. That's why it's more efficient than the alternative.
Why does xs.reverse ::: ys work?
This isn't a "syntax expansion" of reverse_::: — it's two separate method calls chained together:
- First,
xs.reversecreates a new list that's the reverse ofxs. - Then, the
:::method (Scala's list concatenation operator) is called on this reversed list, withysas the argument. This appendsysto the end of the reversedxs.
The end result is identical to xs reverse_::: ys, but since it creates an intermediate reversed list, it's less efficient than the optimized reverse_::: method.
Key Scala Syntax Context
Scala lets you use flexible method names (including underscores and special symbols like :::) and supports infix notation for methods that take exactly one parameter. That's why:
list1 ::: list2is the same aslist1.:::(list2)xs reverse_::: ysis the same asxs.reverse_:::(ys)
The similarity in naming (reverse_::: vs reverse :::) is intentional to signal their equivalent functionality, but they're distinct syntax constructs — not a syntax expansion mechanism at play.
内容的提问来源于stack exchange,提问作者wangt0907

