The beauty of recursion is that you don't need local variables ( var results
).(递归的好处在于您不需要局部变量( var results
)。)
You just pass state as arguments to each recursive iteration:(您只需将状态作为参数传递给每个递归迭代:)
const concat = (xs, y) => xs.concat(y);
const range = (x, y) => {
const rec = (x, y, acc) => x < y ? rec(x + 1, y, concat(acc, x)) : acc;
return rec(x, y, []);
}
ES5 version in case you aren't familiar with the arrow syntax:(ES5版本,以防您不熟悉箭头语法:)
function concat(xs, y) {
return xs.concat(y);
}
function range(x, y) {
function rec(x, y, acc) {
return x < y ? rec(x + 1, y, concat(acc, x)) : acc;
}
return rec(x, y, []);
}
That isn't the most elegant solution though!(那不是最优雅的解决方案!)
With recursion we can simply build up the stack with each recursive call.(使用递归,我们可以在每次递归调用时简单地建立堆栈。) Each stack frame contains a computed partial result.(每个堆栈帧包含一个计算的部分结果。) Then we just need to unwind the stack and attach each partial result to an array:(然后,我们只需要展开堆栈并将每个部分结果附加到数组:)
const range = (x, y) => x < y ? [x].concat(range(x + 1, y)) : [];
Or more functional:(或更实用:)
const concat = (xs, y) => xs.concat(y);
const range = (x, y) => x < y ? concat([x], range(x + 1, y)) : [];
Note that concat([x], range(x + 1, y))
is the recursive case and []
the base case.(请注意, concat([x], range(x + 1, y))
是递归情况, []
是基本情况。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…