Thursday, November 4, 2010

S16

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

  1. // P16 (**) Drop every Nth element from a list.  
  2. // Example:  
  3. // scala> drop(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k))  
  4. // res0: List[Symbol] = List('a, 'b, 'd, 'e, 'g, 'h, 'j, 'k)  
  5.   
  6. // not tail recursive version  
  7. def drop_nottail[T](n: Int, xs: List[T]): List[T] = xs match {  
  8.   case h :: t if (n == 1) => drop_nottail(n - 1, t)  
  9.   case h :: t => h :: drop_nottail(n - 1, t)  
  10.   case Nil => xs  
  11. }  
  12.   
  13. // tail recursive version  
  14. def drop_tail[T](nth: Int, xs: List[T]) = {  
  15.   def recursive[T](n: Int, tail: List[T], acc: List[T]): List[T] = tail match {  
  16.     case h :: t if (n == 1) => recursive(n - 1, t, acc)  
  17.     case h :: t => recursive(n - 1, t, h :: acc)  
  18.     case Nil => acc  
  19.   }  
  20.   recursive(nth, xs, Nil).reverse  
  21. }  
  22.   
  23. // zipwithindex version  
  24. def drop_zipWithIndex[T](nth: Int, xs: List[T]) = {  
  25.   xs.zipWithIndex.flatMap{  
  26.     case (_, i) if (i + 1 == nth) => Nil // drop nth  
  27.     case (e, _) => e :: Nil  
  28.   }  
  29. }  
  30.   
  31. val l: List[Int] = (1 to 100000).toList  
  32. //println(drop_nottail(3, l)) // StackOverflowError  
  33. //println(drop_tail(3, l))  
  34. println(drop_zipWithIndex(3, l))  

解答例
そうまでして1行で書きたいってか!!

No comments:

Post a Comment