Scala 反向列表实现

问题描述 投票:0回答:1

想澄清一下,为什么scala要这样实现反向列表

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

为什么不能这样实施呢?

  @tailrec
  private def reverseRec[A](init: List[A], res: List[A]): List[A] = {
    if(init.isEmpty) return res
    reverseRec[A](init.tail, init.head :: res)
  }

是否有任何其他具有不可变状态的反向实现?

algorithm scala reverse
1个回答
0
投票
def reverseList[A](list: List[A]): List[A] = list match {
  case Nil => Nil
  case head :: tail => reverseList(tail) ::: List(head)
}
© www.soinside.com 2019 - 2024. All rights reserved.