什么是伪递归?

时间:2016-11-02 22:36:45

标签: javascript recursion

鉴于

let doAsynchronousStuff = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("abcdefg"[Math.floor(Math.random() * 7)])
    }, Math.PI * 1 + Math.random())
  })
  .then(data => console.log(data))
  .then(doAsynchronousStuff)
}

为什么考虑.then(doAsynchronousStuff)"伪递归"?

"递归和#34;有什么区别?和"伪递归"?

Context

  

这不是真实的"递归,因为事件循环可以解除   在调用.then回调之前的堆栈 - Alnitak

1 个答案:

答案 0 :(得分:2)

我头脑中的定义为"递归函数"它是自引用的,并且函数结果依赖于自引用调用。

这意味着递归调用必须是"同步"。但那"同步"调用只需要相对于依赖于它的调用,而不是相对于系统。换句话说,递归函数可以在运行循环的每个回合中更深地运行一个调用,并且不需要构建深度堆栈,例如

// recursive but async
function factorial(x) {
    if (x === 0) { return 1; }
    return factorial(x-1).then(function(r) {
        return asyncMultiply(r, x);  // imagining that does r*x asynch
    });
}

由于这样的事情并没有按照我们(我?)的经典教学方式构建调用堆栈,因此将其限定为" pseudo"。