5 ms·
Even many operations performed on a linked list will not be tail recursive if you do them naively. For example, a naive sum function might look like: const
by MrJohz 4y ago
Even many operations performed on a linked list will not be tail recursive if you do them naively. For example, a naive sum function might look like:
const sum = (node: Node): number => {
if (!node.tail) return node.value;
return node.value + sum(node.tail);
}
Even if tail call optimisation were a thing, I'd still expect most recursive functions to be written in a non-tail-recursive fashion, and only later optimised to be tail recursive. But in practice, it's already possible to rewrite those functions in an imperative way when they do become a performance issue.
So in practice, I can see why implementors don't prioritise TCO in Javascript, coming from both directions: there's not a lot of free wins available, because tail calls are rarely the most natural way to express a recursive algorithm; and even if you want to explicitly optimise for them, there's already plenty of ways to optimise an inefficient recursive algorithm if that's necessary.
That said, I can see the value a lot more in a language that's being used as a compilation target, which it probably made more sense when there was more buzz around compile-to-JS languages, and why it makes more sense now with WebAssembly.