4 ms·
I spent the first year or two of my career thinking I needed to Do Recursion because thats what the textbooks said and hey, the language supports tail calls! I
by refulgentis 3y ago
I spent the first year or two of my career thinking I needed to Do Recursion because thats what the textbooks said and hey, the language supports tail calls!
I learned, in the sense you learn by touching a hot stove, that:
A) you can't guarantee the compiler sees it as a tail call and optimizes it.
B) you are now open to a stack overflow appearing in your software at any given point due to compiler changes / your own changes that confuse the compiler, etc.
C) qed, don't do tail calls.
- kriiuuu 3y agoBoth Scala3 and Kotlin allow you to annotate functions with @tailrec which will give you a compiler warning if the compiler can’t optimize. And if you use the xfatal-warn compiler flag the Scala code won’t compile if your function is not tail call.
- FpUser 3y ago>"I spent the first year or two of my career thinking I needed to Do Recursion because thats what the textbooks said" Being an old fart I've learned long ago to not follow self declared prophets. Recursion is a trade off that comes with the cost. Sometimes it makes sense to use it and sometimes (most of the times) it does not. You do what makes you and your customers happy.
- timw4mail 3y agoIterating over tree structures is a pain without recursion, but that's the only situation where I feel I need recursion.
- ivancho 3y agoI don't think you can use tail call recursion for tree walking unless you also manually maintain another stack. And at that point iterative code looks just as readable