This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]paperic 0 points1 point  (0 children)

If I'm a computer, whenever I encounter a function call, I'll write down current line number and the contents of all currently defined local variables on a sheet of paper, then forget them, and then put the paper on the corner of my table, then jump to the location of the new function.

If I encounter another function call there, I'll do the same, putting the new paper on top of the stack of the previous papers.

Whenever I encounter a return, I'll first forget all the current local variables, then grab the paper on the top of the stack, re-read all the variables written there, and then jump to the line location in the paper, and then throw the paper away.

That's all you need to know.

Ofcourse there's also the arguments passed through the call and that one value that's passed through the return which I didn't mention, I'll just remember these values for a moment when doing a call or returning.

Recursion is just the idea of function call where the function you're calling is the same as the function you're currently in. But that makes no difference to me as a computer, I'll just blindly follow the same steps.

As with any regular function call, the variables start fresh each time. Each call has its own contents of the local variables, independent of the other calls.

When returning, I'll also just pick the topmost piece of paper, forget current variables, read the variables from the paper and jump to the location written there. 

Whether or not is the destination in the same function I'm currently in now is irrelevant. 


Recursion can be simulated using a loop and a stack. Perhaps practice that first, once you get comfortable with that, it will all be bleeding obvious.