为什么这个递归执行它的方式? [英] Why does this recursion execute the way it does?
问题描述
代码片段来自 Eloquent Javascript:
Code snippet is from Eloquent Javascript:
function findSolution(target) {
function find(current, history) {
if (current == target) {
return history;
}
else if (current > target) {
return null;
}
else {
return find(current + 5, `(${history} + 5)`) ||
find(current * 3, `(${history} * 3)`);
}
}
return find(1, "1");
}
console.log(findSolution(13));
我调试了代码,看能不能看懂.没用.
I debugged the code to see if I can understand it. Didn't work.
我检查了调用堆栈.似乎在return null;"之后,程序执行了之前的调用,但这次考虑else return为call1 is null || call2".
I inspected the call stack. Seems that after the "return null;", the program executes the previous call, but this time considering else return as "call1 is null || call2".
返回调用堆栈两次后(此时 current 为 6,history 为(1 + 5)"),call1 不再返回 null(因为 current 为 6,history 为(1 + 5)")),那么 current 和 history 怎么只从 call1 中获取值并使用这些值执行 call2 呢?
After going back through the call stack twice (at that point current is 6 and history is "(1 + 5)"), call1 no longer returns null (since current is 6 and history is "(1 + 5)"), so how come current and history just take the values from call1 and execute call2 with those values ?
此外,程序是如何决定首先执行 call2 的,因为此时 call1 不返回 null ?(我正在想象一个无限递归,但无论出于何种原因,显然不是这样)
Also, how does the program decide to execute call2 in the first place, since at that point call1 doesn't return null ? (I am picturing an infinite recursion, but that is for whatever reason, obviously not the case)
我错过了什么?
推荐答案
findSequence(13)
find(1, "1")
find(1 + 5, "(1 + 5)") // this becomes null, because both of its nested stacks are null, because both of their nested stacks are null
find(6 + 5, "((1 + 5) + 5)") // this becomes null, because both of its nested stacks are null
find(11 + 5, "(((1 + 5) + 5) + 5)"
current > target: return null
find(11 * 3, "(((1 + 5) + 5) * 3)"
current > target: return null
find(6 * 3, "((1 + 5) * 3)") // this becomes null, because both of its nested stacks are null
find(18 + 5, "(((1 + 5) * 3) + 5)")
current > target: return null
find(18 * 3, "(((1 + 5) * 3) * 3)")
current > target: return null
find(1 * 3, "(1 * 3)")
find(3 + 5, "((1 * 3) + 5)")
find(8 + 5, "(((1 * 3) + 5) + 5)")
current == target: return "(((1 * 3) + 5) + 5)"
那么,你认为这是准确的吗?
So, would you say this is accurate ?
这篇关于为什么这个递归执行它的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!