を試してみる。
P02 (*) Find the last but one element of a list.
Example:
scala> penultimate(List(1, 1, 2, 3, 5, 8))
res0: Int = 5
def penultimate[T](xs: List[T]): T = xs match {
case x :: _ :: Nil => x
case _ :: tail => penultimate(tail)
case _ => throw new Exception("no such element")
}
def lastNthBuiltln[A](n: Int, ls: List[A]) = {
if(n <= 0) throw new IllegalArgumentException
if(ls.size < n) throw new NoSuchElementException
ls.takeRight(n).head
}
def lastNth[A](n: Int, ls: List[A]): A = {
if(n <= 0) throw new IllegalArgumentException
if(ls.size < n) throw new NoSuchElementException
ls match {
case xs if(ls.length == n) => xs.head
case _ :: tail => lastNth(n, tail)
case Nil => throw new NoSuchElementException
}
}
No comments:
Post a Comment