在Scala中,List是一个高效的数据结构,尤其对于很多递归算法尤其重要。它可以容易在头部添加元素,也可以得到列表的尾部。
val list1 = List(1, 1, 2, 3, 5, 8)
list1: List[Int] = List(1, 1, 2, 3, 5, 8)
def lastBuildin[A](ls: List[A]): A = ls.last
defined function lastBuildin
def lastRecursive[A](ls: List[A]): A = ls match {
case h :: Nil => h
case _ :: tail => lastRecursive(tail)
case _ => throw new NoSuchElementException
}
defined function lastRecursive
lastBuildin(list1)
res3: Int = 8
lastRecursive(list1)
res4: Int = 8
def penultimateBuildin[A](ls: List[A]): A =
if(ls.isEmpty) throw new NoSuchElementException
else ls.init.last
defined function penultimateBuildin
def penultimateRecursive[A](ls: List[A]): A = ls match {
case h :: _ :: Nil => h
case _ :: tail => penultimateRecursive(tail)
case _ => throw new NoSuchElementException
}
defined function penultimateRecursive
penultimateBuildin(list1)
res7: Int = 5
penultimateRecursive(list1)
res8: Int = 5