Wednesday, November 10, 2010

S21

S-99: Ninety-Nine Scala Problemsを試してみる。
勉強のためにListのAPIはなるべく使わない方向。

  1. // P21 (*) Insert an element at a given position into a list.  
  2. // Example:  
  3. // scala> insertAt('new, 1, List('a, 'b, 'c, 'd))  
  4. // res0: List[Symbol] = List('a, 'new, 'b, 'c, 'd)  
  5.   
  6. def insertAt[T](e :T, n: Int, xs: List[T]) = {  
  7.   def r(n: Int, rest: List[T], acc: List[T]): List[T] = (n, rest) match {  
  8.     case (0, h :: t) => acc.reverse ::: List(e) ::: rest  
  9.     case (_, h :: t) => r(n - 1, t, h :: acc)  
  10.   }  
  11.   if(n < 0 || xs.size <= n) throw new NoSuchElementException else r(n, xs, Nil)  
  12. }  
  13.   
  14. def insertAt2[T](e :T, n: Int, xs: List[T]) = {  
  15.   if(n < 0 || xs.size <= n) throw new NoSuchElementException  
  16.   val splitted = xs.splitAt(n)  
  17.   splitted._1 ::: List(e) :::  splitted._2  
  18. }  
解答例
君、それ好きだよね。

No comments:

Post a Comment