jvm-tail-recursion icon indicating copy to clipboard operation
jvm-tail-recursion copied to clipboard

Any advantage of using this with Kotlin?

Open LifeIsStrange opened this issue 4 years ago • 2 comments

I wonder how does this compare to kotlin tailrec keyword implementation.

LifeIsStrange avatar Apr 22 '20 16:04 LifeIsStrange

I haven't used Kotlin, but here's what I presume based on the docs for tailrec. (https://kotlinlang.org/docs/reference/functions.html#tail-recursive-functions)

There's no verification. If you apply the optimization provided by this library, you won't get a negative feedback if a method cannot be optimized. Accidental breakage may happen if you're not careful.


Kotlin performs weaker analysis. The following is not optimized:

val eps = 1E-10 // "good enough", could be 10^-15
tailrec fun findFixPoint(x: Double = 1.0): Double
{
        if (Math.abs(x - Math.cos(x)) < eps) 
    		return x 
    	else {
    		val r = findFixPoint(Math.cos(x));
    		return r
        }
}

You can see that the variable r is directly returned, however, a warning is issued about the function not being optimized. See this playground link.

This library supports this.


For Kotlin:

You cannot use tail recursion when there is more code after the recursive call, and you cannot use it within try/catch/finally blocks.

This is the same for this library. You can use the optimization before and after try-catch blocks, but not inside them.


This what I've found based on my understanding of Kotlins tailrec, but there might be more to it.

Sipkab avatar Apr 22 '20 17:04 Sipkab

Kotlin performs weaker analysis.

VERY interesting, I wonder if Kotlin compiler developpers could take inspiration / reuse your work or even do a collab with you! Anyway you show a suboptimal case that should be fixed, I will open a Kotlin issue when I find the time

LifeIsStrange avatar Apr 22 '20 19:04 LifeIsStrange