Я пытаюсь взять эту рабочую рекурсивную функцию (ниже) ...
![Problem A description](https://i.stack.imgur.com/yZAhb.png)
def cubeIt(n: Int): Int = {
println("acc:"+acc);
println("n: "+n);
if(n==0){
return 0;
}
else if(n>0){
return cubeIt(n-1) + 3*(n*n) - 3*n + 1
}
else{
return cubeIt(n+1) - 3*(n*n) - 3*n - 1
}
}
... и превратить ее в функция хвостовой рекурсии.
![Problem B description](https://i.stack.imgur.com/lQhQb.png)
import scala.annotation.tailrec
@tailrec
def cubeItHelper(n: Int, acc: Int): Int = { /* Implement cubeIt as a tail recursion */
if(n==0){
return acc;
}
if(n>0){
return cubeItHelper(n-1, acc+(3*(n*n) - 3*n + 1));
}
else{
return cubeItHelper(n+1, (acc+((-3)*(n*n) - 3*n - 1)));
}
}
/*-
This is the main function that the users will use.
It should call the helper with the correct initial value of acc argument.
Just replace the ??? with the correct initial value for the acc argument.
-*/
def cubeItTail(n: Int): Int = {
if(n==0){
return 0;
}
else{
cubeItHelper(n, 0);
}
}
С помощью приведенного выше кода она выдает следующее:
acc:0
n: 5
acc:61
n: 4
acc:98
n: 3
acc:117
n: 2
acc:124
n: 1
......
первые четыре строки теста завершены правильно
n: -100
acc:-29701
n: -99
acc:-58808
n: -98
acc:-87327
...(goes forever)
Это тестовые утверждения (они зависают от последнего):
assert(cubeItTail(5) == 125)
assert(cubeItTail(-5) == -125)
assert(cubeItTail(-3) == -27)
assert(cubeItTail(0) == 0)
assert( (-100 to 100).forall( x => (cubeItTail(x) == x * x * x)), "Test Passed!")
Буду признателен, если кто-нибудь скажет мне, что я делаю здесь неправильно.