Yes, stacks of nested subs are super-cool. But, uh, why bother writing all recursive code this way? I don't see any gain in efficiency (if anything, creating all those subs might slow things down a tad), and it introduces an extra level of "WTF?" to people reading the code.
On the other hand, if you're writing tail-recursive code, this is a great way of not exposing an accumulator variable to the rest of the world. For example (untested):
sub fact
{
my $fact_tr; # needs to exist before it gets assigned to
$fact_tr = sub {
my ($v, $r) = @_;
return 1 if $v < 2; # oversimplified
$fact_tr->($v-1, $v * $r);
}; # thanks ihb for pointing out the missing semi
$fact_tr->(@_, 1);
}
Also, have a look at Just Another Godel, Escher, Bach hacker.
Edit: Separated declaration and use of $fact_tr. Thanks ihb!
--
F
o
x
t
r
o
t
U
n
i
f
o
r
m
Found a typo in this node? /msg me
% man 3 strfry
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|