[英]What's the difference between ::: and ++ for Lists?
Given two lists a
and b
, what's the difference between a ::: b
and a ++ b
? 给定两个列表
a
和b
, a ::: b
和a ++ b
之间a ::: b
什么区别? I suspected one of these operators would simply call the other, but in fact, the implementations look completely different: 我怀疑其中一个操作符只是调用另一个,但实际上,实现看起来完全不同:
def :::[B >: A](prefix: List[B]): List[B] =
if (isEmpty) prefix
else if (prefix.isEmpty) this
else (new ListBuffer[B] ++= prefix).prependToList(this)
override def ++[B >: A, That](that: GenTraversableOnce[B])
(implicit bf: CanBuildFrom[List[A], B, That]): That = {
val b = bf(this)
if (b.isInstanceOf[ListBuffer[_]])(this ::: that.seq.toList).asInstanceOf[That]
else super.++(that)
}
From a usage perspective, should I prefer a ::: b
or a ++ b
? 从使用角度来看,我应该更喜欢
a ::: b
还是a ++ b
? From an implementation perspective, is there a specific reason why one of these operators doesn't simply call the other? 从实施的角度来看,有一个特定的原因,为什么其中一个运营商不会简单地呼叫另一个?
The difference is in that you can only use :::
on 2 lists -- this operation is only available on the List
datatype. 不同之处在于您只能在2个列表上使用
:::
- 此操作仅在List
数据类型上可用。 Since lists are sequences, it acts as a concatenation operators for lists. 由于列表是序列,因此它充当列表的串联运算符。
The ++
method is more general - it allows creating a union of any two collections. ++
方法更通用 - 它允许创建任何两个集合的并集。 That may be two sets, in which case it acts as a union, or two sequences in which case it acts as a concatenation. 这可能是两组,在这种情况下,它充当联合,或两个序列,在这种情况下,它充当连接。
There is no semantic difference between ++
and :::
for 2 lists -- :::
is the variant of ++
for functional lists that should look more familiar to functional programmers. 对于2个列表,
++
和:::
之间没有语义差异 - :::
是函数列表的++
的变体,对函数式程序员来说应该更熟悉。
The if
statement you see in the ++
implementation is an optimization -- if both this
collection and that
collection are lists, just use the list concatenation operator :::
to add the two lists together. 您在
++
实现中看到的if
语句是一个优化 - 如果this
集合和that
集合都是列表,只需使用list concatenation operator :::
将两个列表一起添加。 Otherwise, use the generic implementation of ++
that adds all the elements of this
and that
collection to an appropriate builder for the type That
. 否则,使用
++
的通用实现,它将this
和that
集合的所有元素添加到类型That
的适当构建器中。
So, the relevant difference for lists is performance -- for functional lists you don't need to traverse the second list as a generic ++
implementation would - only the nodes of the first list need to be reinstantiated to create a new functional list. 因此,列表的相关差异是性能 - 对于功能列表,您不需要像通用
++
实现那样遍历第二个列表 - 只需要重新实例化第一个列表中的节点以创建新的功能列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.