Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Passing anon sub as param

by tmoertel (Chaplain)
on Jul 28, 2005 at 22:21 UTC ( #479155=note: print w/replies, xml ) Need Help??


in reply to Passing anon sub as param

The reason BrowserUk passed the node-printing code as an anonymous subroutine was to separate the traversal logic from the node-processing logic. With this separation, we can use the same traversal logic for other purposes, and we can use the same node-processing logic with other traversals.

Consider the following nested-array-style tree and logic to traverse it:

my $tree = [ 1 , [ 2 , 3 , [ 4 , [ 5 ] , 6 ] ] , 7 ] ; sub traverse { my ($nodefn, $tree, $depth) = @_; $depth ||= 0; $depth++; for (@$tree) { ref() ? traverse( $nodefn, $_, $depth ) : $nodefn->( $_, $depth ); } }
We can combine this traversal logic with task-specific node-processing logic. For example, to count the nodes in the tree, we might use logic like this:
sub count_nodes { my $count; traverse( sub { $count++ }, @_ ); $count; } print count_nodes($tree), $/; # 7
For other jobs we can easily "plug in" other node-processing code. Here is code to print a single indented node:
sub print_node { my ($leaf, $depth) = @_; print " " x ($depth - 1), "* $leaf", $/; }
We just plug it into traverse to print the tree's outline:
traverse( \&print_node, $tree ); # * 1 # * 2 # * 3 # * 4 # * 5 # * 6 # * 7
Going further, we can plug in new traversal logic, too. Here is logic to do a breadth-first traversal – all the leaves at each depth are processed before going deeper.
sub bfs_traverse { my ($nodefn, $tree, $depth) = @_; $depth ||= 0; $depth++; my @leaves = grep !ref(), @$tree; my @branches = grep ref(), @$tree; $nodefn->( $_, $depth ) for @leaves; bfs_traverse( $nodefn, [map @$_, @branches], $depth ) if @branches; }
Now we can use this traversal logic with our existing print_node logic to outline the tree in breadth-first order:
bfs_traverse( \&print_node, $tree ); # * 1 # * 7 # * 2 # * 3 # * 4 # * 6 # * 5
By this point, I hope you can see the answer to your second question: by keeping traversal and node-processing concerns separated and by combining them through a well-defined interface (here, function passing), we can mix and match logic. If we want a breadth-first outline, we don't need to write a breadth-first outline function; we can just combine a breadth-first traversal with a node-printing processor.

Cheers,
Tom

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://479155]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2022-11-30 21:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?