C tail call optimization

Statements like “C doesn’t perform tail call elimination” make no sense. As you correctly noted yourself, things like this depend entirely on the implementation. And yes, any decent implementation can easily turn tail-recursion into [an equivalent of] a cycle. Of course, C compilers do not normally give any guarantees about what optimizations will and what … Read more

What is tail-recursion elimination?

Tail call elimination is an optimization that saves stack space. It replaces a function call with a goto. Tail recursion elimination is the same thing, but with the added constraint that the function is calling itself. Basically, if the very last thing a function A does is return A(params…) then you can eliminate the allocation … 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

Does Swift implement tail call optimization? and in mutual recursion case?

The best way to check is to examine the assembly language code generated by the compiler. I took the code above and compiled it with: swift -O3 -S tco.swift >tco.asm The relevant part of the output .globl __TF3tco3sumFTSiSi_Si .align 4, 0x90 __TF3tco3sumFTSiSi_Si: pushq %rbp movq %rsp, %rbp testq %rdi, %rdi je LBB0_4 .align 4, 0x90 … Read more

Why would code actively try to prevent tail-call optimization?

My guess here is that it’s to ensure that __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ is in the stack trace for debugging purposes. It has __attribute__((no inline)) which backs up this idea. If you notice, that function just goes and bounces to another function anyway, so it’s a form of trampoline which I can only think is there with such … Read more

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

One reason I’ve seen in the past for not implementing TCO (and it being seen as difficult) in Java is that the permission model in the JVM is stack-sensitive and thus tail-calls must handle the security aspects. I believe this was shown to not be an obstacle by Clements and Felleisen [1] [2] and I’m … 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