简体   繁体   English

咖喱形式的递归函数可以是尾递归吗?

[英]Can a recursive function in curried form be tail recursive?

Given is the following recursive map function: 给定以下递归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])); 

Obviously, the recursive call h(h) isn't the last action of the recursive function. 显然,递归调用h(h)并不是递归函数的最后动作。 But when the stack is unwound, everything that happens is that the finished accumulator is returned without any further changes or operations. 但是,当展开堆栈时,发生的所有事情都是返回完成的累加器,而没有任何进一步的更改或操作。 Is map against my expectations tail recursive? map是否符合我的期望尾部递归?

the recursive call h(h) isn't the last action of the recursive function 递归调用h(h)不是递归函数的最后一个动作

h(h) is not a recursive call. h(h)不是递归调用。 The …(tail) is the recursive call, and yes, it's in a tail position. …(tail)是递归调用,是的,它处于尾部位置。

This might get more obvious if you drop that overcomplicated U combinator (or at least used the Y combinator right away): 如果您丢弃过于复杂的U组合器(或至少立即使用Y组合器),则可能会变得更加明显:

const map = f => {
  const mapF = acc => ([head, ...tail]) => head === undefined
    ? acc
    : mapF([...acc, f(head)])(tail);
  return mapF([]);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM