Hacker News new | ask | show | jobs
by whatever1 465 days ago
I don’t understand the obsession of people with recursion. Sure it’s a cute math trick, it makes you feel smart, but it is an undebuggable mess with a ton of gotchas that lead to stack overflows.

Let the math to the math guys who never ship a product.

6 comments

I use recursion a fair bit just because it's the easiest solution that requires the least thought. If I have a tree structure from e.g a JSON parser, or a directory tree, or an HTML node tree, what more debuggable options are there, realistically?

Re-writing recursive algorithms to be non-recursive typically requires less obvious code, where you make your own ad-hoc stack to keep track of where you are; essentially implementing the call stack manually.

In contexts where DoS or stack smashing is a concern because the input is attacker-controlled, it's often way easier to add a depth parameter and error at a certain depth than to rewrite the naturally recursive algorithm into iterative style. But tree structures are so naturally recursive that it's easy to end up with accidental unbounded recursion in complex real-world situations.

Keeping track of where you are is THE feature.

You can manage memory and compute budget so that your cute algo does not go rogue. On top of that very often you don’t have to explore the entire tree, and there is custom logic at each step to decide whether you want to proceed or not with exploration.

Programmers like recursion because some algorithms are much, much more pleasant to write this way. Others are easier to write iteratively. Both are easy to do wrong.

Example: depth-first tree walking algorithms. Implicit stack makes it trivial to express as recursion.

It is not smart, or special, or something.

If your data structures are recursive, it makes sense your algorithms are too. It makes the code tidy and simpler to reason about. Plenty of times your code becomes "obviously correct".
I write a genealogy app (family history). Recursion is the foundation of the code, and permeates everywhere. The call stack can go 200 deep or more (~4,000 yrs). The code has been successfully running on millions of desktops for thirty years, and has never caused a crash or infinite loop because of recursion.

The secret is to check at every step that there is no "he's his own grandpa" loops in the user's tree, where (s)he inadvertently makes one of a person's descendants, also his ancestor. This happens sometimes because re-using the same names can cause confusion.

Recursion is like magic :o)

Recursions are super useful for dealing with certain data types, notably nested grammar parsing. Sure, it has gotcha, but that can be extremely readable.

I don't think we should ban recursions altogether, but remember that there exist associated risks, and consider them.

The alternative is just recursion with more steps