I was wondering if it could be possible for a sub to return a recursive closure. Of course this turns out to be possible, although, to the best of my efforts, not in "one step", see e.g. the following code:
sub mkrecsub { my $k=shift; my @memoize = ( $k => [0,1] ); my $tmp = sub { my ($n, $func) = @_; return $memoize[$k][$n] if defined $memoize[$k][$n]; $memoize[$k][$n] = $func->($n-1, $func) + $func->($n-2, $func); }; sub { $tmp->(shift, $tmp) }; } my $Fib = mkrecsub(1); print $Fib->($_) for 1..73;
Now I wonder if there is/could be (could not find any!) some sort of
identifier that refers to the current (anomynous) sub; say, something
like __SUB__
or __THIS__
, to be used like this:
sub { ... __SUB__->(...); }