无法理解 Ruby 中的递归

Trouble understanding recursion in Ruby

我正在关注一个关于递归的视频,它在 Ruby

首先,将序列附加到数组的代码很容易理解:

def append(ary, n)
  return ary if n < 0
  ary << n
  append(ary, n-1)
end

append([], 5)
=> [5, 4, 3, 2, 1, 0]

我不明白的是 reverse_append 函数出现的时间:

01 def reverse_append(ary, n)
02   return ary if n < 0
03   reverse_append(ary, n-1)
04   ary << n
05   return ary
06 end

我理解函数 reverse_append 是这样做的:

我不明白的是,如果第 02 行说如果 n 小于 0,则 return 数组(据我了解,这将是空的),为什么第 04 行会完全执行。这个的流程图是什么?

递归的关键:同一个函数有很多调用处于活动状态。每个调用都有自己的局部变量。 return 当前创新仅 return。

调用函数树如下所示

reverse_append([], 2)
..reverse_append([], 1)
....reverse_append([], 0)
......reverse_append([], -1)
......returns []
....[] << 0
....returns [0]
..[0] << 1
..-> [0, 1]
 [0, 1] << 2
 -> [0, 1, 2]

你的reverse_append可以改写为:

def reverse_append(ary, n)
  return ary if n < 0
  reverse_append(ary, n-1)
  ary << n
end

这使得与 append(ary, n) 的区别更明显的是您执行 << 与递归调用的顺序。 append() 表示 "If I haven't gotten to a negative value, concatenate my n to the array, and then get the array that results from concatenating all smaller values of n and return it",而 reverse_append() 表示 "If I haven't gotten to a negative value, get the array that results from concatenating all smaller values of n, and then concatenate my n to the result and return it." 如果您仔细考虑一下,您应该会发现这决定了附加值的顺序。