Skip to content

Instantly share code, notes, and snippets.

@moritz
Created July 10, 2012 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moritz/3086115 to your computer and use it in GitHub Desktop.
Save moritz/3086115 to your computer and use it in GitHub Desktop.
Generic tree folder in Perl 6
sub visit($root, &children, :&pre, :&post, :&assemble = -> *%{ Nil }) {
my ($pre, $post, @children);
$pre = pre($root) if defined ⪯
@children = children($root).map: {visit $_, &children, :&pre, :&post, :&assemble};
$post = post($root, :@children) if defined &post;
return assemble(:$pre, :$post, :@children, :node($root));
}
=begin pod
=head1 visit
sub visit($root, &children; :&pre, :&post, :&assemble = -> *% { Nil })
Visits C<$root> and, recursively, all of its children, as returned from
C<children($root)>. Runs C<pre> before and C<post> after visiting the children.
If an named argument was passed for C<assemble>, that routine is called with
named arguments C<node>, C<children>, C<pre> and C<post>, and its return value
is returned from sub C<visit>.
=end pod
say visit($=pod[0], { .content if .isa(Pod::Block) }, :pre(*.Str),
:assemble(-> :$pre, :@children, *% { join ' ', $pre, @children; }));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment