Can Tail Call Optimization and RAII Co-Exist?

Taken at face-value, it would certainly seem like RAII works against TCO. However, remember that there are a number of ways in which the compiler can “get away with it”, so to speak. The first and most obvious case is if the destructor is trivial, meaning that it is the default destructor (compiler-generated) and all … Read more

Avoiding stack overflow (with F# infinite sequences of sequences)

You should definitely check out http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/FSharp.PowerPack/Microsoft.FSharp.Collections.LazyList.html but I will try to post a more comprehensive answer later. UPDATE Ok, a solution is below. It represents the Morris sequence as a LazyList of LazyLists of int, since I presume you want it to be lazy in ‘both directions’. The F# LazyList (in the FSharp.PowerPack.dll) has three … Read more

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

Why is my Scala tail-recursion faster than the while loop?

Test results (after reducing array size to 20000000) Under Java 1.6.22 I get 151 and 122 ms for tail-recursion and while-loop respectively. Under Java 1.7.0 I get 55 and 101 ms So under Java 6 your while-loop is actually faster; both have improved in performance under Java 7, but the tail-recursive version has overtaken the … 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