Perl Monk, Perl Meditation PerlMonks

### Comment on

 Need Help??

I tried to see if I could find a generic way of transforming a recursive function into an iterator. I found a method that's can be applied rather mechanically.

Let's say your recursive function visits a tree in preorder. The following would be the a non-iterative solution:

```sub visit_preorder(&\$) {
my (\$visitor, \$node) = @_;
my (\$val, \$l, \$r) = @\$node;
\$visitor->() for \$val;
&visit_preorder(\$visitor, \$l) if defined \$l;
&visit_preorder(\$visitor, \$r) if defined \$r;
}

Change the visitor code to return \\$val; where \$val is the data to return from the iterator. return \@val; is also acceptable if you wish to return more than one value.

Break up the function where a recursive call is made. Return each block as a function as follows:

```sub visit_preorder {
my (\$node) = @_;
my (\$val, \$l, \$r) = @\$node;
return (
sub { return \\$val;                                    },
sub { return visit_preorder(\$l) if defined \$l; return; },
sub { return visit_preorder(\$r) if defined \$r; return; },
);
}

In this case, it can be simplified a little.

```sub visit_preorder {
my (\$node) = @_;
my (\$val, \$l, \$r) = @\$node;
return (
\\$val,
defined(\$l) ? sub { return visit_preorder(\$l); } : (),
defined(\$r) ? sub { return visit_preorder(\$r); } : (),
);
}

Now we just need an engine to drive this.

```sub make_iter {
my \$f = shift @_;
my @todo = \$f->(@_);
return sub {
while (@todo) {
my \$todo = shift @todo;
if (ref(\$todo) eq 'CODE') {
unshift @todo, \$todo->();
} elsif (ref(\$todo) eq 'ARRAY') {
return @\$todo;
} else {
return \$\$todo;
}
}
return;
};
}

Finally, an example caller.

```{
#      a
#     / \
#    b   e
#   / \   \
#  c   d   f

my \$tree = [
'a',
[
'b',
[
'c',
undef,
undef,
],
[
'd',
undef,
undef,
],
],
[
'e',
undef,
[
'f',
undef,
undef,
],
],
];

my \$iter = make_iter(\&visit_preorder, \$tree);
while (my (\$name) = \$iter->()) {
print(\$name);
}
print("\n");
}

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

• Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
• Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
• Read Where should I post X? if you're not absolutely sure you're posting in the right place.
• Posts may use any of the Perl Monks Approved HTML tags:
a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
• You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
 For: Use: & & < < > > [ [ ] ]
• Link using PerlMonks shortcuts! What shortcuts can I use for linking?

Create A New User
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2017-11-23 13:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
In order to be able to say "I know Perl", you must have:

Results (335 votes). Check out past polls.

Notices?