in reply to recursion basics

Hello wrinkles,

The thing about recursion is, (and this is what trips up most learners) it does NOT compute results UNTIL it has reached the terminating condition. That is, it would go on accumulating non-computed results and builds the final value once it reaches the end of the recursion condition.

Now, it should be seen that for recursion to happen - it always needs two factors in place:

Hopefully, I can make this clear by using a well known factorial example.

sub factorial { my ($n) = shift; if ($n < 2) { return 1; } else { return $n * factorial($n - 1); } }

Now, consider what would happen if you were to invoke it as: factorial(5). You have the terminating condition and the means to compute the next thunk. It should look something like below:

factorial(5)
5 * factorial(4)
5 * 4 * factorial(3)
5 * 4 * 3 * factorial(2)
5 * 4 * 3 * 2 * factorial(1)
5 * 4 * 3 * 2 * 1
= 120

Understood so far? Let's take a look at binary:

Hopefully, it's all a bit more clear now. You can read more about recursion on Wikipedia here.

Replies are listed 'Best First'.
Re^2: recursion basics
by wrinkles (Pilgrim) on Jun 23, 2015 at 07:13 UTC
    I will have to look at all this info with fresh eyes in the morning, but my overall impression is that the code and data structure is build "outside-in", then evaluated "inside-out" to reach the final return.

    This is almost making sense! Thanks again!