创建 Scala 列表的首选方法 [英] Preferred way to create a Scala list

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

问题描述

在 Scala 中有几种构造不可变列表的方法(请参阅下面的人为示例代码).您可以使用可变 ListBuffer,创建一个 var 列表并修改它,使用 tail递归方法,可能还有其他我不知道的方法.

There are several ways to construct an immutable list in Scala (see contrived example code below). You can use a mutable ListBuffer, create a var list and modify it, use a tail recursive method, and probably others that I don't know about.

本能地,我使用 ListBuffer,但我没有这样做的充分理由.是否有首选或惯用的方法来创建列表,或者是否有一种方法最适合另一种方法的情况?

Instinctively, I use the ListBuffer, but I don't have a good reason for doing so. Is there a preferred or idiomatic method for creating a list, or are there situations that are best for one method over another?

import scala.collection.mutable.ListBuffer

// THESE are all the same as: 0 to 3 toList.
def listTestA() ={
    var list:List[Int] = Nil

    for(i <- 0 to 3) 
        list = list ::: List(i)
    list
}


def listTestB() ={
    val list = new ListBuffer[Int]()

    for (i <- 0 to 3) 
        list += i
    list.toList
}


def listTestC() ={
    def _add(l:List[Int], i:Int):List[Int] = i match {
        case 3 => l ::: List(3)
        case _ => _add(l ::: List(i), i +1)
    }
    _add(Nil, 0)
}

推荐答案

ListBuffer 是一个可变列表,具有固定时间追加,以及固定时间转换为 List.

ListBuffer is a mutable list which has constant-time append, and constant-time conversion into a List.

List 是不可变的,并且具有恒定时间前置和线性时间后置.

List is immutable and has constant-time prepend and linear-time append.

您构建列表的方式取决于您将使用该列表的算法以及您获取元素以创建它的顺序.

How you construct your list depends on the algorithm you'll use the list for and the order in which you get the elements to create it.

例如,如果您以与将要使用的时间相反的顺序获取元素,那么您可以只使用 List 并进行前置.无论您是使用尾递归函数、foldLeft 还是其他东西,都不是真正相关的.

For instance, if you get the elements in the opposite order of when they are going to be used, then you can just use a List and do prepends. Whether you'll do so with a tail-recursive function, foldLeft, or something else is not really relevant.

如果获取元素的顺序与使用它们的顺序相同,那么如果性能至关重要,ListBuffer 很可能是更可取的选择.

If you get the elements in the same order you use them, then a ListBuffer is most likely a preferable choice, if performance is critical.

但是,如果您不在关键路径上并且输入足够低,您总是可以稍后反转列表,或者只是foldRight,或反转输入,这是线性时间.

But, if you are not on a critical path and the input is low enough, you can always reverse the list later, or just foldRight, or reverse the input, which is linear-time.

不要做的是使用List并附加到它.这会给您带来比在最后添加和反转更糟糕的性能.

What you DON'T do is use a List and append to it. This will give you much worse performance than just prepending and reversing at the end.

这篇关于创建 Scala 列表的首选方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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