Scala第02题:获取前一个索引元素
发布时间
阅读量:
阅读量
//Find the last but one element of a list.
//List列表中找出倒数第二个元素
package com.yl.problem
object Pro02 {
//01、内置方法解决
def method01[A](ls: List[A]): A = {
if (ls.isEmpty) throw new NoSuchElementException
//init: 返回List[A],除了最后一个元素的所有元素构成的列表,然后.last即为所求元素
else ls.init.last
}
//02、模式匹配解决
def method02[A](ls: List[A]): A = ls match{
case h :: _ :: Nil => h //若是两个元素的List 则返回h
case _ :: tail => method02(tail) //后续列表tail继续循环执行至剩余两个元素的列表时(即case h...)
case _ => throw new NoSuchE
全部评论 (0)
还没有任何评论哟~
