Created
October 31, 2012 15:35
-
-
Save daiksy/3987714 to your computer and use it in GitHub Desktop.
コラッツ数列のScala実装(末尾再帰版)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 『すごいHaskell』で実装例が出ていたコラッツ数列をScalaで実装 | |
* | |
* https://gist.github.com/3986524 が末尾再帰になってないので | |
* なおしてみた. | |
* | |
* コラッツ数列とは: | |
* ・任意の自然数から開始する. | |
* ・数が1ならば,終了. | |
* ・数が偶数ならば,2で割る. | |
* ・数が奇数ならば,3倍して1を足す. | |
* ・新しい値でこのアルゴリズムを繰り返す. | |
* | |
**/ | |
object collatzApp extends App { | |
collatz(1) foreach println // 結果は [1] | |
collatz(10) foreach println // 結果は [10,5,16,8,4,2,1] | |
object collatz { | |
import scala.annotation.tailrec | |
def apply(i: Int) = calc(i :: Nil).reverse | |
@tailrec | |
private def calc(xs: List[Int]): List[Int] = { | |
xs.head match { | |
case 1 => xs | |
case n if (n % 2 == 0) => calc(n / 2 :: xs) | |
case n => calc((n * 3) + 1 :: xs) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment