6 ms·
Scala has been using this technique for years with its scala.annotation.tailrec annotation. Regardless, it's cool to see this implemented as a bytecode pass.
by 1932812267 1y ago
Scala has been using this technique for years with its scala.annotation.tailrec annotation. Regardless, it's cool to see this implemented as a bytecode pass.
- gavinray 1y agoKotlin as well, with the "tailrec" keyword, e.g. "tailrec fun fibonacci()" https://kotlinlang.org/docs/functions.html#tail-recursive-functions https://kotlinlang.org/docs/functions.html#tail-recursive-fu... Kotlin also has a neat other tool, "DeepRecursiveFunction<T, R>" that allows defining deep recursion that is not necessarily tail-recursive. Really useful if you wind up a problem that is most cleanly solved with mutual recursion or similar: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-deep-recursive-function/ https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-deep-r...
- deepsun 1y agoInteresting, does it depend on Kotlin compiler or it can be implemented in Java as well?
- gavinray 1y agoThe "DeepRecursiveFunction<T,R>" could be implemented in Java. The Kotlin implementation leverages Kotlin's native coroutines and uses continuations. It'd require a bit of engineering to get something working in native Java I'd imagine, even with the new JDK Structured Concurrency API offering you a coroutines alternative. On the other hand, "tailrec" is a keyword and implemented as a compiler optimization. The closest I've seen in Java is a neat IntelliJ plugin that has a transformation to convert recursive method calls into imperative loops with a stack frame. This transformation and resulting tool was the result of someone's thesis, it's pretty cool: https://github.com/andreisilviudragnea/remove-recursion-inspection https://github.com/andreisilviudragnea/remove-recursion-insp...