Practical Uses of Recursion
For those of you who have been working for some time I'd like to find out what practical uses you have seen for recursion. I'm not talking about college courses or what you see in tutorials, but what programmers use it for in real-world programs such as system, applications, etc.
There are only three reasons that I have ever used it in my c or c++ programs To navigate through disk directory trees
Parse binary trees
Some sorting algorithms
Can you add to the above list?
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
>what programmers use it for in real-world programs such as system, applications, etc.
Recursive descent parsing comes to mind.
>Parse binary trees
Actually, my experience is that nearly every recursive algorithm when working with binary trees is better written iteratively. This improves the performance[1], footprint guarantees[2], reliability[3], and flexibility[4].
[1] Removal of recursion is one of the first steps in optimizing a recursive algorithm.
[2] It's harder to guess how much memory will be used when variable stack frames enter the picture.
[3] Unless the height of the tree is limited to below the remaining stack size at the point where recursion begins (imagine trying to guarantee this), the possibility of a stack overflow is always going to be present.
[4] A good example of this is re-entrant iteration. I have yet to see a good way to break off recursive iteration and then start it back at the same place (without coroutine support, of course), or change the direction in which you traverse the tree mid-traversal (at least, not without being painfully ugly). With an iterative approach, both of these (very useful) tasks are trivial.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>Pass a function as an argument and call that.
By "good way", I meant something that's both easy to use and easy to follow, as well as works across the board without changes. Your suggestion only works for very specific cases and does not scale well.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Recursion is never(*) used in embedded systems because of the indeterminate amount of stack space required.
A stack overrun on an embedded platform just trashes something else, rather than killing the runaway process with an out-of-stack exception.
Stacks are also of a fixed size; there's no VM to extend the space if you need it.
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953