Scala練習題01:找出列表中最後一個元素
// Scala:Find the last element of a list.
// Scala:找出列表中最後一個元素
// 示例:
// scala> last(List(1, 1, 2, 3, 5, 8))
// res0: Int = 8
package com.yl.problem
object Problem01 {
def main(args: Array[String]){
//1、Scala內建的方法實現 List.last
def lastBuiltin[A](ls: List[A]): A = ls.last
println("Scala內建的方法實現結果:" + lastBuiltin(List(1, 1, 2, 3, 5, 8)))
println("Scala內建的方法實現結果:" + lastBuiltin(List(1, 3, 4, 5, 7, 9)))
//2、利用Scala的模式匹配實現
def lastRecursive[A](ls: List[A]): A = ls match {
case h :: Nil => h //一個元素則直接獲取
case _ :: tail => lastRecursive(tail) //剩餘元素列表繼續迴圈執行,直至剩最後一個元素為止
case _ => throw new NoSuchElementException //其他情況丟擲異常
}
println("Scala模式匹配實現的結果:" + lastRecursive(List(1, 1, 2, 3, 5, 8)))
println("Scala模式匹配實現的結果:" + lastRecursive(List(1, 3, 4, 5, 7, 9)))
}
}
執行結果:
Scala內建的方法實現結果:8
Scala內建的方法實現結果:9
Scala模式匹配實現的結果:8
Scala模式匹配實現的結果:9