将项目添加到不可变的 Seq

发布于 2024-12-18 06:50:00 字数 586 浏览 1 评论 0原文

假设我有一个字符串序列作为输入,我想获得一个新的不可变的 Seq ,它由输入的元素和一个项目 "c" 组成。以下是我发现有效的两种方法:

  1. assert(Seq("a", "b", "c") == Seq("a", "b") ++ Seq("c") ")) - 这个问题是,似乎仅仅为了操作而实例化一个临时序列 (Seq("c")) 是多余的,并且会导致开销
  2. assert(Seq("a", "b", "c") == List("a", "b") ::: "c" :: Nil) - 这个限制了输入集合的类型为 List,因此 Seq("a", "b") ::: "c" :: Nil 将不起作用。另外,实例化一个 Nil 似乎也可能会导致开销

我的问题是:

  1. 还有其他方法来执行此操作吗?
  2. 哪一个更好?
  3. 不允许 Seq("a", "b") ::: Nil 不是 Scala 开发人员的一个缺陷吗?

Say, I have a sequence of strings as an input and I want to get a new immutable Seq which consists of elements of the input and an item "c". Here are two methods that I've discovered to be working:

  1. assert(Seq("a", "b", "c") == Seq("a", "b") ++ Seq("c")) - the problem with this one is that it seems that instantiating a temporary sequence (Seq("c")) just for the sake of the operation is rendundant and will result in overhead
  2. assert(Seq("a", "b", "c") == List("a", "b") ::: "c" :: Nil) - this one restricts the type of input collection to be a List, so Seq("a", "b") ::: "c" :: Nil won't work. Also it seems that instantiating a Nil may aswell result in overhead

My questions are:

  1. Is there any other way of performing this operation?
  2. Which one is better?
  3. Isn't Seq("a", "b") ::: Nil not being allowed a flaw of Scala's developers?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

明明#如月 2024-12-25 06:50:00

使用 :+(附加)运算符创建一个new Seq,使用:

val seq = Seq("a", "b") :+ "c"
// seq is now ("a","b","c")

注意::+ 将创建一个新的 Seq 对象。
如果你有

val mySeq = Seq("a","b")

并且你将调用

mySeq :+ "c"

mySeq 仍然是 ("a","b")

请注意,Seq 的某些实现更合适比其他人追加。 List 针对前置进行了优化。 Vector 具有快速的追加和前置操作。

:::List 上的一个方法,它需要另一个 List 作为其参数 - 您认为它接受其他类型的优点是什么顺序?它必须将其他类型转换为List。如果您知道 List 对于您的用例来说是有效的,那么请使用 ::: (如果必须的话)。如果您想要多态行为,请使用通用的 ++

使用 Nil 没有实例化开销;你不实例化它,因为它是一个单例。

Use the :+ (append) operator to create a new Seq using:

val seq = Seq("a", "b") :+ "c"
// seq is now ("a","b","c")

Note: :+ will create a new Seq object.
If you have

val mySeq = Seq("a","b")

and you will call

mySeq :+ "c"

mySeq will still be ("a","b")

Note that some implementations of Seq are more suitable for appending than others. List is optimised for prepending. Vector has fast append and prepend operations.

::: is a method on List which requires another List as its parameter - what are the advantages that you see in it accepting other types of sequence? It would have to convert other types to a List. If you know that List is efficient for your use case then use ::: (if you must). If you want polymorphic behaviour then use the generic ++.

There's no instantiation overhead to using Nil; you don't instantiate it because it's a singleton.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文