ScalaByExampleで、末尾再帰にしてみろとのことだったので、してみた。
def factorial2(n: int) : int = {
factorialIter(1, n)
}
def factorialIter(sum: int, n: int) : int = {
if (n == 1) sum else factorialIter(sum * n, n - 1)
}
で、バイトコードを見てみる。
public int factorialIter(int, int); Code: Stack=3, Locals=3, Args_size=3 0: iload_2 1: iconst_1 2: if_icmpeq 16 5: iload_1 6: iload_2 7: imul 8: iload_2 9: iconst_1 10: isub 11: istore_2 12: istore_1 13: goto 0 16: iload_1 17: ireturn
おぉ、ループになってますな。
P.S. Scala的には、こうかな。
def factorial2(n: int) : int = {
def factorialIter(sum: int, n: int) : int = {
if (n == 1) sum else factorialIter(sum * n, n - 1)
}
factorialIter(1, n)
}
トラックバック[0]
コメント[0]
投稿者 shanai : 2008/05/14 0:15:38 JST








