3 ms·
Thanks for investigating that! An accumulator is when we add an extra parameter to hold the "loop variable", like this: bool doit(int n, bool acc) {
by ufo 5y ago
Thanks for investigating that!
An accumulator is when we add an extra parameter to hold the "loop variable", like this:
bool doit(int n, bool acc)
{
if (n == 0) return acc;
else return doit(n-1, !acc);
}
bool isEven(int n)
{
return doit(n, true);
}
The function is now tail-recursive and behaves similarly to this loop:
bool acc = true;
while (n != 0) {
acc = !acc;
n = n - 1;
}
return acc;
According to the comment on the top of the file, apparently llvm can create this accumulator variable if the operation is associative and commutative. That's because after introducing the accumulator, the evaluation order is outside->inside instead of inside->outside.