Scala 列表连接,::: vs ++ [英] Scala list concatenation, ::: vs ++

查看:19
本文介绍了Scala 列表连接,::: vs ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

:::++ 在 Scala 中连接列表有什么区别吗?

Is there any difference between ::: and ++ for concatenating lists in Scala?

scala> List(1,2,3) ++ List(4,5)
res0: List[Int] = List(1, 2, 3, 4, 5)

scala> List(1,2,3) ::: List(4,5)
res1: List[Int] = List(1, 2, 3, 4, 5)

scala> res0 == res1
res2: Boolean = true

来自文档看起来 ++ 更通用,而 ::::List 特定的.提供后者是因为它在其他函数式语言中使用吗?

From the documentation it looks like ++ is more general whereas ::: is List-specific. Is the latter provided because it's used in other functional languages?

推荐答案

Legacy.List 最初被定义为看起来像函数式语言:

Legacy. List was originally defined to be functional-languages-looking:

1 :: 2 :: Nil // a list
list1 ::: list2  // concatenation of two lists

list match {
  case head :: tail => "non-empty"
  case Nil          => "empty"
}

当然,Scala 以一种特别的方式发展了其他集合.当 2.8 出现时,集合被重新设计以实现最大的代码重用和一致的 API,以便您可以使用 ++ 来连接任意两个集合——甚至是迭代器.但是,List 必须保留其原始运算符,除了一两个已弃用的运算符.

Of course, Scala evolved other collections, in an ad-hoc manner. When 2.8 came out, the collections were redesigned for maximum code reuse and consistent API, so that you can use ++ to concatenate any two collections -- and even iterators. List, however, got to keep its original operators, aside from one or two which got deprecated.

这篇关于Scala 列表连接,::: vs ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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