Friday, November 12, 2010

S22

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

  1. // P22 (*) Create a list containing all integers within a given range.  
  2. //  Example:  
  3. // scala> range(4, 9)  
  4. // res0: List[Int] = List(4, 5, 6, 7, 8, 9)  
  5.   
  6. def rangeTail(from: Int, to: Int) = {  
  7.   def r(current: Int, acc: List[Int]): List[Int] = {  
  8.     if(current <= to) r(current + 1, current :: acc)  
  9.     else acc.reverse  
  10.   }  
  11.   r(from, Nil)  
  12. }  
  13.   
  14. def rangeBuiltin(from: Int, to: Int) = List.range(from, to + 1).toList  
解答例
unfoldRightっていう発想はなかった。 だけど、末尾再帰じゃないじゃないか。 これじゃすぐstackoverflowだ。 ということで、unfoldRightの末尾再帰版を書いてみた。
  1. def unfoldRightTail[A, B](s: B)(f: B => Option[(A, B)]): List[A] = {  
  2.   def recursive(s: B, acc: List[A]): List[A] = {  
  3.     f(s) match {  
  4.       case None         => acc.reverse  
  5.       case Some((r, n)) => recursive(n, r :: acc)  
  6.     }  
  7.   }  
  8.   recursive(s, Nil)  
  9. }  
  10. def rangeFunctionalTail(start: Int, end: Int): List[Int] =  
  11.   unfoldRightTail(start) { n =>  
  12.     if (n > end) None  
  13.     else Some((n, n + 1))  
  14.   }  

No comments:

Post a Comment