给出以下递归map
函数:
const U = f => f(f);
const map = f => U(h => acc => ([head, ...tail]) => head === undefined
? acc
: h(h)([...acc, f(head)])(tail))([]);
const xs = [1,2,3,4,5];
console.log(map(x => x * x)([1,2,3,4,5]));
显然,递归调用h(h)
并不是递归函数的最后一个 Action 。但是当堆栈被展开时,所发生的一切都是返回完成的累加器,而不进行任何进一步的更改或操作。 map
是否违反了我的预期尾递归?
最佳答案
the recursive call
h(h)
isn't the last action of the recursive function
h(h)
不是递归调用。 …(tail)
是递归调用,是的,它位于尾部位置。
如果您放弃过于复杂的 U
组合器(或者至少立即使用 Y
组合器),这可能会变得更加明显:
const map = f => {
const mapF = acc => ([head, ...tail]) => head === undefined
? acc
: mapF([...acc, f(head)])(tail);
return mapF([]);
};
关于javascript - 柯里化(Currying)形式的递归函数可以是尾递归吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38467951/