Consider the recursive subroutine append_until_exhausted. The recursion occurs in the middle of the body. I want to place it at the end for further processing, that is to say a simple tail call (without any optimisation, which in Perl typically involves a goto). You can change anything but the signature of the subroutine and the two helper subroutines.
The algorithms involving numerics look stupid because are a condensation/obfuscation of my real code, but the code execution path/structure of subroutine calls is unchanged.
use 5.032;
use strictures;
use experimental qw(signatures);
# Returns mostly one value, sometimes multiple,
# and an occasional end condition which will cause
# the recursion to end because then the for loop will
# iterate over an empty list.
# This sub is also called from elsewhere,
# do not change, do not inline.
sub some_complicated_computation($foo) { # → ArrayRef[$foo]
return [] if $foo > 45;
return $foo % 5
? [$foo + 1]
: [$foo + 2, $foo + 3];
}
# do not inline
sub make_key($foo) { # → Str
chr(64 + $foo / 5)
}
sub append_until_exhausted($foo, $appendix) { # → HashRef[ArrayRef[$foo]]
my $computed = some_complicated_computation($foo);
for my $new_foo ($computed->@*) {
{
push $appendix->{make_key $new_foo}->@*, $new_foo;
}
__SUB__->($new_foo, $appendix);
}
return $appendix;
}
my $new_appendix = append_until_exhausted(
7, # start value for foo
{ dummy => [], dummy2 => [], dummy3 => [], }
);
The goal here is for me to understand the principle so I can apply it in similar situations and in similar languages. It does not help if you suggest some {Sub::*, B::*, XS} magic.
Let's start with a simple example.
To make something tail-recursive, you need to pass the information needed to perform the tail operation along with the call.
This particular solution relies on the fact that multiplication is commutative. (We replaced
1*2*3*4with1*4*3*2.) So we still need a generic approach.A generic approach would involve passing the tail as a callback. This means that
becomes
This gives us the following:
This is basically how Promises work.
What you have is a lot trickier because you have multiple recursive calls. But we can still apply the same technique.
We can avoid all the extra copies of
$appendixas follows:Perl doesn't perform tail-call elimination, and function calls are rather slow. You'd be better off using an array as a stack.
This performs the work in the same order as the original:
If you don't mind doing the complicated computation out of order (while still preserving the result), the above simplifies to the following: