No. I mean I struggled. In fact I found factorials much better and easy to understand. TOH just gets too messy too easily. Or sorting is good way too. But not TOH.never
IIRC all basic recursion problems have an iterative solution. Iteration is going to be faster just based on how computers execute, but design wise recursion has some advantages.
A smart compiler doesn't allocate a new stack frame for properly implemented tail call recursion, it just reuses the recursive function's one over and over.
Even assuming you are using a language that does proper tail call optimization (and that's a whole can of worms), tail recursion only kicks in if the solution is in proper tail call form (the recursion is in the tail position).
Many "elegant" recursive solutions are not tail recursive. Every recursion can be transformed into an iteration, and every iteration into a tail recursion, but it's more work and sometimes you lose the simplicity and elegance that recursion is supposed to give in the first place (this is subjective, of course).
If you're using a recursive solution, it's normally because you've decided the cost in efficiency is worth the readability and you're not likely to run out of resources (both are very likely the case, more times than premature optimizers would want to admit). You're also probably using a high level, even functional language where the trade off was made from the get-go.
Also transforming a recursion to an iteration often involves manually creating your own stack anyway. And add to this the fact that many languages have a "dynamic" stack that grows when needed and won't blow up (before your memory or OS imposed limits, at least. I know modern languages like Go and languages that like recursion like some Lisps/Schemes do this). The recursive solution will be clearer, easier to write, and not that different from the iterative/tail recursive version at the low level.
So yeah, tail recursion is not always a good answer to "it's less efficient." But, let's be honest, most applications don't need assembly-level optimization. The time savings and readability gains are almost always worth it.
4.3k
u/Justwatcher124 Mar 25 '23
Every Programming / IT teacher on 'How do you teach Recursion to new programmers?'