DEV Community

Discussion on: Why YOU should learn Recursion

 
johncip profile image
jmc

you would not be able to go through a tree easily with a while

Well, traversal, at least, is straightforward to do iteratively with an explicit stack.


IMO "recursion should always be bounded" doesn't make for good advice. The risk of infinite loops is higher when iterating, because a recursive version has to stop once the call stack is blown. (Excepting tail calls in the handful of languages that optimize them.)

So I think that leaves us with "loops and recursion should always be bounded" -- which IMO isn't appropriate for most domains.

I do agree that cycle detection is useful. And I think you're saying that often when one encounters recursive code, it's doing something to a tree -- if so, I agree there too, depending on language. I also think that a forgotten base case doesn't stand out visually the way that while(true) does.

Even so, I don't think we can generalize from "trees can have accidental cycles" to "all recursion should come with a kill switch." I think the right advice is "don't forget the base case" and "do cycle detection as necessary."