2 ms·
Iteration is also self-referential. New iterations refer to prior values, and jump backwards to prior code. I think the way to teach recursion to programmers w
by kazinator 9y ago
Iteration is also self-referential. New iterations refer to prior values, and jump backwards to prior code.
I think the way to teach recursion to programmers who have mastered iteration is to teach the tricks for transforming loops into tail recursion: start by equating the self reference with the establishment of new values for the loop variables and the backward branch.
E.g. given a working dot product:
double dot(double *a, double *b, size_t n)
{
double acc = 0;
while (n-- != 0)
acc += *a++ + *b++;
return acc;
}
We identify the loop variables: a, b, n, and acc. First, we can rewrite this using a form of "goto with parameters".
#define dot_rec(label, na, nb, nn, nacc) { \
/* capture argument evaluations into fresh temporary variables */ \
double *tna = (na), *tnb = (nb); \
size_t tnn = (nn); \
double tnacc = (nacc); \
/* store temporaries to loop variables, and jump backward */ \
a = tna; b = tnb; n = tnn; acc = tnacc; \
goto label; \
}
double dot(double *a, double *b, size_t n)
{
double acc = 0.0;
again:
if (n != 0) /* we can now use (n > 0) since n isn't decremented! */
dot_rec(again, a + 1, b + 1, n - 1, acc + *a * *b);
return acc;
}
Thus if n is not zero, we update a with a + 1, b with b + 1, n with n - 1, and the accumulator by adding a + b.
The dot_rec macro ensures that the expression * a is not affected by a receiving a + 1; it mimics the binding of argument expression values to fresh arguments.
From that we can go to recursion:
double dot_rec(double *a, double *b, size_t n, double acc)
{
if (n > 0)
return dot_rec(again, a + 1, b + 1, n - 1, acc + *a * *b);
return acc;
}
double dot(double *a, double *b, size_t n)
{
return dot_rec(a, b, n, 0.0);
}
Get people comfortable with mechanically converting iteration to recursion, even in cases where recursion isn't all that nice, and requires additional parameters and possibly the splitting of a function API into a non-recursive and recursive part.
Then go into non-tail recursion; recursion in which the parent actually does something with the return value other than just return it: those true divide-and-conquer problems.
Then mutual recursion among two or more functions, starting with something trivial like odd(n) and even(n) that mutually tail recurse.
- JadeNB 9y ago> a working dot product: double dot(double *a, double *b, size_t n) { double acc = 0; while (n-- != 0) acc += *a++ + *b++; return acc; } For a working dot product, I think you mean acc += *a++ + *b++; to be acc += *a++ * *b++; (That's how your recursive version does it, anyway.)
- kazinator 9y ago> I think you mean Oh well, s/dot product/"dot sum"/ :) :) :) > how your recursive version does it See, everyone? Recursion irons out bugs!