【问题标题】:reverse implementation Seq反向实现Seq
【发布时间】:2013-04-14 18:55:15
【问题描述】:

SeqLike.scala 类中有一个名为reverse 的函数,它可以反转一个序列。例如它使List(1,2,3,4) 成为`List(4,3,2,1)

在源码中,描述是:

def reverse: Repr = {
var xs: List[A] = List() //Line 1
for (x <- this)
  xs = x :: xs
val b = newBuilder ////Line 4
b.sizeHint(this)
for (x <- xs)
  b += x
b.result
}

我不明白的是:第 (1-3) 行完成了这项工作。但是为什么它会创建一个新的builder,然后向它添加元素以返回。只需 Line[1-3] 就足够了

【问题讨论】:

    标签: scala


    【解决方案1】:

    第 1-3 行生成一个List。但是reverse 不应该返回任何旧的Seq,而是返回相同类型的Seq。因此,如果它实际上是一个列表,则不需要额外的构建器步骤;否则它会。 (如果你查看List 的实现,它不会做额外的工作。)

    override def reverse: List[A] = {
      var result: List[A] = Nil
      var these = this
      while (!these.isEmpty) {
        result = these.head :: result
        these = these.tail
      }
      result
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-09
      • 1970-01-01
      • 1970-01-01
      • 2014-09-29
      • 2014-01-10
      • 1970-01-01
      • 1970-01-01
      • 2020-01-15
      相关资源
      最近更新 更多