简体   繁体   中英

Can a recursive function in curried form be tail recursive?

Given is the following recursive map function:

 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. 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?

the recursive call h(h) isn't the last action of the recursive function

h(h) is not a recursive call. The …(tail) is the recursive call, and yes, it's in a tail position.

This might get more obvious if you drop that overcomplicated U combinator (or at least used the Y combinator right away):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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