在perl中重写一个递归函数,以便它可以在列表上下文中使用

发布于 2024-10-20 20:26:03 字数 896 浏览 1 评论 0原文

考虑 Moose::Cookbook 中开发的二叉树::Basics::Recipe3

要检索所有节点按顺序,我可以添加下面的子例程到 BinaryTree 包

sub pre_order {
  my ($self,$aref) = @_;

  push @$aref, $self->node;

  pre_order($self->left,$aref) if $self->has_left;
  pre_order($self->right,$aref) if $self->has_right;
}

子例程必须像这样使用:

my $btree = BinaryTree->new;
#add some nodes

#then later...
my @nodes_in_preorder;
$btree->pre_order(\@nodes_in_preorder);

我必须如何更改子例程才能使用如下语法:

my @nodes_in_preorder = $btree->pre_order();

以便能够执行

for ($btree->pre_order()) { #bla bla } 

稍后的操作。

这有道理吗,还是我太迂腐了?

Consider the binary tree developed in Moose::Cookbook::Basics::Recipe3

To retrieve all nodes in preorder, I could add the following subroutine to the BinaryTree package

sub pre_order {
  my ($self,$aref) = @_;

  push @$aref, $self->node;

  pre_order($self->left,$aref) if $self->has_left;
  pre_order($self->right,$aref) if $self->has_right;
}

The sub would have to be used like this:

my $btree = BinaryTree->new;
#add some nodes

#then later...
my @nodes_in_preorder;
$btree->pre_order(\@nodes_in_preorder);

How would i have to change the subroutine to be able to use syntax like the below:

my @nodes_in_preorder = $btree->pre_order();

in order to be able to do things like

for ($btree->pre_order()) { #bla bla } 

later on.

Does this make sense, or am I being to pedantic?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

撧情箌佬 2024-10-27 20:26:03

怎么样:

sub pre_order {
  my $self = shift;
  return ($self->node,
    $self->has_left ? $self->left->pre_order : (),
    $self->has_right ? $self->right->pre_order : ());
}

How about:

sub pre_order {
  my $self = shift;
  return ($self->node,
    $self->has_left ? $self->left->pre_order : (),
    $self->has_right ? $self->right->pre_order : ());
}
眼眸印温柔 2024-10-27 20:26:03

您可以只更改调用者:

for ( do { my @preorder; $btree->pre_order(\@preorder); @preorder } ) {

或者简单地更改代码,如下所示:

sub pre_order {
    my ($self,$aref) = @_;

    push @$aref, $self->node;

    $self->left->pre_order($aref) if $self->has_left;
    $self->right->pre_order($aref) if $self->has_right;

    return @$aref if wantarray;
}

无需将数组引用传递给外部调用;将自动创建一个,因此您的代码将正常工作(TM):

for ( $self->pre_order() ) {

You could just change the caller:

for ( do { my @preorder; $btree->pre_order(\@preorder); @preorder } ) {

Or simply change the code like so:

sub pre_order {
    my ($self,$aref) = @_;

    push @$aref, $self->node;

    $self->left->pre_order($aref) if $self->has_left;
    $self->right->pre_order($aref) if $self->has_right;

    return @$aref if wantarray;
}

No need to pass an array reference to the outer call; one will be created automatically, so your code will Just Work (TM):

for ( $self->pre_order() ) {
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文