Created
July 9, 2012 06:54
-
-
Save tattyamm/3074686 to your computer and use it in GitHub Desktop.
scalaの末尾再帰サンプル
This file contains 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
/** | |
* 末尾再帰サンプル | |
*/ | |
object sample { | |
def main(args: Array[String]) { | |
println(sumByTailCall(100)) | |
} | |
@scala.annotation.tailrec //これをつけると、末尾再帰でないメソッドをコンパイルエラーにしてくれる。 | |
private def sumByTailCall(next: Int, total: Int = 0): Int = { | |
if (next == 0) total | |
else sumByTailCall(next - 1, total + next) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment