[英]Getting two last elements of the list WITHOUT using reverse method? [scala]
如何在不使用Scala中使用反向方法的情况下获得列表的最后两个元素? (仅第一,第二,尾巴,头部)。 我想像“ list.tail.head”那样输入sth,但是它不起作用。 有任何想法吗?
只需使用takeRight
List(1, 2, 3).takeRight(2)
res0: List[Int] = List(2, 3)
我假设您不想使用诸如reverse,takeRight等之类的东西。
import scala.annotation.tailrec
@tailrec
def take2[T](l: List[T]): Option[List[T]] = l match {
case Nil | _ :: Nil => None
case _ :: _ :: Nil => Some(l)
case _ :: xs => take2(xs)
}
如果您有一种算法需要快速访问集合中的最后两个元素,请考虑使用List以外的其他方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.