Tuesday, November 9, 2010

S20

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

  1. // P20 (*) Remove the Kth element from a list.  
  2. // Return the list and the removed element in a Tuple. Elements are numbered from 0.  
  3. // Example:  
  4. // scala> removeAt(1, List('a, 'b, 'c, 'd))  
  5. // res0: (List[Symbol], Symbol) = (List('a, 'c, 'd),'b)  
  6.   
  7. def removeAt[T](i: Int, xs: List[T]) =  
  8.   if(i < 0 || xs.size <= i) throw new NoSuchElementException  
  9.   else (xs.zipWithIndex.filter{_._2 != i}.map{_._1}, xs(i))  
  10.   
  11. def removeAtR[T](i: Int, xs: List[T]) = {  
  12.   def r(i: Int, xs: List[T], acc: List[T]): (List[T], T) = (i, xs) match {  
  13.     case (0, h :: t) => (acc.reverse ::: t, h)  
  14.     case (i, h :: t) => r(i - 1, t, h :: acc)  
  15.   }  
  16.   if(i < 0 || xs.size <= i) throw new NoSuchElementException else r(i, xs, Nil)  
  17. }  
解答例の上のやつ、いいね。

No comments:

Post a Comment