所以我有这个递归函数将两个数字相乘,很简单。斯卡拉尾递归
def mul(n: Int, m: Int):Int =
if(m > 1) n + mul(n, dec(m))
else n
现在我试图把它变成一个尾递归函数,我想这一点:
def mulWithTail(n: Int, m: Int):Int = {
@tailrec
def iter(result: Int, x: Int):Int =
if(x == 0) result
else result + iter(result, dec(x))
iter(n, m)
}
不过,我得到以下错误:
error: could not optimize @tailrec annotated method iter: it contains a recursive call not in tail position
else result + iter(result, dec(x))
问题:你能向我解释为什么会出现这个错误吗?我应该如何重构我的代码?
DEC()只是一个BTW – Phillip