假设某个编程语言不支持函数调用本身，如何实现递归

``````function factorial(n) {
if (n === 1) return 1;
return n * factorial(n-1); // 调用了本身
}

factorial(4); // 24``````

方式1

``````function _factorial(self, n) {
if (n === 1) return 1;
return n * self(self, n-1);
}

function factorial(n) {
return _factorial(_factorial, n);
}

factorial(4); // 24``````

方式2：YCombinator

``````const _factorial = (getSelf) => (n) => {
if (n === 1) return 1;
const self = getSelf();
return n * self(n-1);
}

function YCombinator(F) {
const f_gen = (self) => F(() => self(self));
return f_gen(f_gen);
}

const factorial = YCombinator(_factorial);

factorial(4); // 24``````

YCombinator是通用的，可以求解任何高阶函数的不动点。YCombinator可以帮助我们在不支持递归的语言中实现递归。比如，斐波那契数的计算：

``````const _fib = (getSelf) => (n) => {
if (n === 0 || n === 1) return n;
const self = getSelf();
return self(n-1) + self(n-2);
}

function YCombinator(F) {
const f_gen = (self) => F(() => self(self));
return f_gen(f_gen);
}

const fib = YCombinator(_fib);

// 斐波那契数列：0 1 1 2 3 5 8
fib(6); // 8``````

参考资料

csRyan

So you're passionate? How passionate? What actions does your passion lead you to do? If the heart...

1.1k 声望
181 粉丝
0 条评论