想澄清一下,为什么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)
}
是否有任何其他具有不可变状态的反向实现?
def reverseList[A](list: List[A]): List[A] = list match {
case Nil => Nil
case head :: tail => reverseList(tail) ::: List(head)
}