函数确实在y = 0时返回1,但是这个值被返回给调用者——Square(x,1)——它返回一个值给它的调用者@987654323 @,等等。
(递归函数的最大秘密在于它们的工作方式与非递归函数完全一样。)
我认为最好的理解方法之一是使用替换方法。
看看Square (3,2)。用它们的值替换函数定义中的x 和y 给出
if 2 = 0 then 1 else 3 * Square (3, 2-1)
2 显然不是 0,所以我们需要弄清楚 Square (3, 1) 是什么,然后才能继续进行乘法运算。
重复同样的过程:
if 1 = 0 then 1 else 3 * Square (3, 1-1)
条件仍然为假,所以继续Square (3,0)。
if 0 = 0 then 1 else 3 * Square (3, 0-1)
现在条件为真,所以我们知道Square (3,0) 是1。
后退一级并替换:
if 1 = 0 then 1 else 3 * 1
所以,Square (3,1) 是 3。再次替换:
if 2 = 0 then 1 else 3 * 3
得到 9,这是你所期望的。
您也可以考虑这个(无限的)非递归函数序列:
...
fun Square_3 (x, y) = if y = 0 then 1 else x * Square_2 (x, y-1)
fun Square_2 (x, y) = if y = 0 then 1 else x * Square_1 (x, y-1)
fun Square_1 (x, y) = if y = 0 then 1 else x * Square_0 (x, y-1)
fun Square_0 (x, y) = if y = 0 then 1 else x * Square_minus1(x, y-1)
fun Square_minus1 (x, y) = ...
然后想想Square_2(3, 2) 是如何工作的。 Square(3,2) 的工作方式完全相同。
(顺便说一句,你的函数有一个很奇怪的名字。你可能想重命名它。)