恕我直言,解释递归的最佳方法是逐步完成它,看看实际发生了什么。另一件有帮助的事情是添加 return 语句,尤其是如果您来自 Java 之类的语言,因为它更容易理解正在发生的事情。
您的返回函数如下所示:
def sum(xs: List[Int]): Int = {
if(xs.isEmpty)
return 0
else
return xs.head + sum(xs.tail)
}
在您的情况下,您有一个函数可以对列表中的所有整数求和。
所以让我们想象一下,您使用具有以下值 (1,2,3) 的列表调用了函数
函数将如何表现?
第一个函数调用如下所示:
if(xs.isEmpty) // false - it has 3 elements (1,2,3)
return 0 // skipped
else
return 1 + sum((2,3)) // xs.head is changed with 1 and xs.tail is list with (2,3)
第二次调用现在使用列表 (2,3):
if(xs.isEmpty) // false - it has 2 elements (2,3)
return 0 // skipped
else
return 2 + sum((3)) // xs.head is changed with 2 and xs.tail is list with (3)
Trird 调用现在使用列表 (3):
if(xs.isEmpty) // false - it has 1 elements (3)
return 0 // skipped
else
return 3 + sum(()) // xs.head is changed with 3 and xs.tail is empty list now
第四次调用是空列表:
if(xs.isEmpty) // true
return 0 // Recursion termination case triggered
所以现在我们的 sum 调用堆栈看起来像这样:
sum((1,2,3))
where sum = 1 + sum((2,3))
where sum = 2 + sum((3))
where sum = 3 + sum(())
where sum = 0
我们只是开始返回值:
sum((1,2,3))
where sum = 1 + 5
where sum = 2 + 3
where sum = 3 + 0
所以我们最终得到 sum((1,2,3)) = 6
这就是我们不需要存储“中间结果”的原因,因为计算总和从末尾开始并向后滚动。