Wednesday, November 3, 2010

S14

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

  1. // P14 (*) Duplicate the elements of a list.  
  2. // Example:  
  3. // scala> duplicate(List('a, 'b, 'c, 'c, 'd))  
  4. // res0: List[Symbol] = List('a, 'a, 'b, 'b, 'c, 'c, 'c, 'c, 'd, 'd)  
  5.   
  6. def duplicate[T](xs: List[T]): List[T] = xs match {  
  7.   case h :: t => h :: h :: duplicate(t)  
  8.   case Nil => xs  
  9. }  
  10.   
  11. def duplicate_tail[T](xs: List[T]) = {  
  12.   def recursive(ys: List[T], acc: List[T]): List[T] = ys match {  
  13.     case Nil => acc  
  14.     case h :: t => recursive(t, h :: h :: acc)  
  15.   }  
  16.   recursive(xs, Nil).reverse  
  17. }  
  18.   
  19. def duplicate_map[T](xs: List[T]): List[T] = xs.flatMap{ x => x :: x :: Nil}  
  20.   
  21. //val l = List('a, 'b, 'c, 'c, 'd)  
  22. val l = 1 to 1000000 toList  
  23.   
  24. println(duplicate_tail(l))  
  25. println(duplicate_map(l))  
  26. println(duplicate(l)) // StackOverFlow  

解答例
そうですよね。

No comments:

Post a Comment