を試してみる。
// P03 (*) Find the Kth element of a list.
// By convention, the first element in the list is element 0.
//
// Example:
// scala> nth(2, List(1, 1, 2, 3, 5, 8))
// res0: Int = 2
def nth[T](n: Int, xs: List[T]): T = xs match { case Nil => throw new NoSuchElementException case _ if(n < 0 || xs.length <= n) => throw new IllegalArgumentException case h :: _ if(n == 0)=> h case _ :: tail => nth(n - 1, tail) }
解答例はタプルにしてmatch-caseしてる。
No comments:
Post a Comment