3 ms·
>Because that's how you transform a recursive call into an iterative one, not nested for loops. I came to understand recursion through nested for-loops, though
by edmccard 9y ago
>Because that's how you transform a recursive call into an iterative one, not nested for loops.
I came to understand recursion through nested for-loops, though, but that might just be a historical accident. In the summer of 1988 I had written a Mastermind solver in Microsoft Quickbasic[1] for the specific case of 4 "pegs". At each guess, I used for-loops nested 4 deep to build a structure representing the possible remaining solutions (for all possibilities of the first peg, check all for the second peg, etc.) Then I wanted to extend it to work with variable numbers of pegs; after spending most of that summer trying to figure out a loop-based solution, I discovered that subroutines could call themselves and it hit me that I could have a function that took the possibilities already computed for a peg, and then called itself with those applied to the next peg.
So I've always thought of recursion as a way to have arbitrarily deeply nested loops.
[1] Believe it or not, it did support recursive functions!
- deleted 9y ago[deleted]
- catmanjan 9y agoQuickbasic was great, fond memories of typing out hundreds of DATA statements for game sprites.
- heavenlyblue 9y agoBut in reality recursion is an arbitrarily nested context that has nothing to do with loops per se (and that's why sometimes it requires the stack and sometimes it does not).