Skip to content

Instantly share code, notes, and snippets.

@tattyamm
Created July 9, 2012 06:54
Show Gist options
  • Save tattyamm/3074686 to your computer and use it in GitHub Desktop.
Save tattyamm/3074686 to your computer and use it in GitHub Desktop.
scalaの末尾再帰サンプル
/**
* 末尾再帰サンプル
*/
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