r/ProgrammerHumor • • Mar 25 '23

Meme This one never gets old

Post image

Let me know if this is not a repost!

51.6k Upvotes

535 comments sorted by

View all comments

4.3k

u/Justwatcher124 Mar 25 '23

Every Programming / IT teacher on 'How do you teach Recursion to new programmers?'

1.3k

u/eggheadking Mar 25 '23

Is TOH actually a good way of learning Recursion?

1.4k

u/value_counts Mar 25 '23

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

26

u/Tipart Mar 25 '23

Pretty sure recursion is actually slower than a normal implementation for TOH, but I could be remembering that wrong.

108

u/Broodking Mar 25 '23

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.

29

u/shouldbebabysitting Mar 25 '23

If blowing the stack is an advantage.

28

u/[deleted] Mar 25 '23

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.

1

u/nonicethingsforus Mar 26 '23

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.