tail-recursive function appending element to list

The following is an implementation of tail recursion modulo cons optimization, resulting in a fully tail recursive code. It copies the input structure and then appends the new element to it, by mutation, in the top-down manner. Since this mutation is done to its internal freshly-created data, it is still functional on the outside (does … Read more

Why does the JVM still not support tail-call optimization?

Diagnosing Java Code: Improving the Performance of Your Java Code (alt) explains why the JVM does not support tail-call optimization. But although it is well known how to automatically transform a tail-recursive function into a simple loop, the Java specification doesn’t require that this transformation be made. Presumably, one reason it is not a requirement … Read more

Does Haskell have tail-recursive optimization?

Haskell uses lazy-evaluation to implement recursion, so treats anything as a promise to provide a value when needed (this is called a thunk). Thunks get reduced only as much as necessary to proceed, no more. This resembles the way you simplify an expression mathematically, so it’s helpful to think of it that way. The fact … Read more

How do I replace while loops with a functional programming alternative without tail call optimization?

An example in JavaScript Here’s an example using JavaScript. Currently, most browsers do not support tail call optimisation and therefore the following snippet will fail const repeat = n => f => x => n === 0 ? x : repeat (n – 1) (f) (f(x)) console.log(repeat(1e3) (x => x + 1) (0)) // 1000 … Read more

What is tail call optimization?

Tail-call optimization is where you are able to avoid allocating a new stack frame for a function because the calling function will simply return the value that it gets from the called function. The most common use is tail-recursion, where a recursive function written to take advantage of tail-call optimization can use constant stack space. … Read more