jvm-tail-recursion
jvm-tail-recursion copied to clipboard
Any advantage of using this with Kotlin?
I wonder how does this compare to kotlin tailrec keyword implementation.
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.
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