我是Scala新手,开始学习尾递归。我了解到函数式编程中的尾递归是命令式编程中迭代(for循环)的对应部分:
对列表元素求和的简单 C++ 循环:
uint32_t sum = 0;
for (size_t i = 0; i < list.length(); ++i) {
sum += list[i];
}
Scala递归等价物:
def listSum(list: List[Int]): Int = {
def listSumHelper(list: List[Int], sum: Int): Int = {
if (list.isEmpty) sum
else listSumHelper(list.tail, sum + list.head)
}
listSumHelper(list, 0)
}
问题: 嵌套 for 循环的 scala 递归等价物是什么?
uint32_t sum = 0;
for (size_t i = 0; i < list.width(); ++i) {
for (size_t j = j < list.height(); ++j) {
sum += list[i][j];
}
}