勉強のためにListのAPIはなるべく使わない方向。
- // P22 (*) Create a list containing all integers within a given range.
- // Example:
- // scala> range(4, 9)
- // res0: List[Int] = List(4, 5, 6, 7, 8, 9)
- def rangeTail(from: Int, to: Int) = {
- def r(current: Int, acc: List[Int]): List[Int] = {
- if(current <= to) r(current + 1, current :: acc)
- else acc.reverse
- }
- r(from, Nil)
- }
- def rangeBuiltin(from: Int, to: Int) = List.range(from, to + 1).toList
unfoldRightっていう発想はなかった。 だけど、末尾再帰じゃないじゃないか。 これじゃすぐstackoverflowだ。 ということで、unfoldRightの末尾再帰版を書いてみた。
- def unfoldRightTail[A, B](s: B)(f: B => Option[(A, B)]): List[A] = {
- def recursive(s: B, acc: List[A]): List[A] = {
- f(s) match {
- case None => acc.reverse
- case Some((r, n)) => recursive(n, r :: acc)
- }
- }
- recursive(s, Nil)
- }
- def rangeFunctionalTail(start: Int, end: Int): List[Int] =
- unfoldRightTail(start) { n =>
- if (n > end) None
- else Some((n, n + 1))
- }
No comments:
Post a Comment