Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of tailrec in Kotlin?

Tags:

kotlin

tailrec optimizes functions where there is tail recursion. Why doesn't the compiler just optimize it anyway?

C compilers optimize for tail recursion. You don't have to mark the method as having tail recursion. The compiler just notices that the last operation is recursive. And that's that.

Why does this seemingly excessive keyword exist? Have I missed something? Is it purely for the convenience of the compiler, and not the user?

like image 693
HelloWorld Avatar asked Aug 01 '18 16:08

HelloWorld


3 Answers

The keyword tells the compiler that the implementation of the function is required to be tail-recursive, and causes the compiler to report an error if the function is not actually tail-recursive. It protects the user from situations when a change to the implementation of the function causes it to no longer be tail-recursive, and causes an unexpected drop in performance (or a complete failure in production due to a stack overflow error).

like image 152
yole Avatar answered Sep 30 '22 14:09

yole


I'll go ahead and guess that this is to be able to more deliberately write tail-recursive functions. By requiring the keyword explicitly, you'll know that the compiler optimization will definitely happen (you won't be left guessing if the compiler optimized your function successfully or if you'll get a stack overflow at runtime), plus your code won't even compile if you break the rules of tail recursion for the function you've maked with tailrec, as the doc states:

To be eligible for the tailrec modifier, a function must call itself as the last operation it performs.

like image 43
zsmb13 Avatar answered Sep 30 '22 16:09

zsmb13


Recall official Kotlin documentation just says that :

When a function is marked with the tailrec modifier and meets the required form, the compiler optimises out the recursion, leaving behind a fast and efficient loop based version instead

Which strongly suggests that this conversion to a loop is not warranted to take place if the tailrec keyword is not present.

like image 40
incises Avatar answered Sep 30 '22 16:09

incises