如何在 Perl 和 Moose 中创建不可变对象的循环图?
这看起来显然是一个绝望的情况,但是有没有一个技巧可以在 Perl 中创建不可变对象的循环图?像这样的事情:
package Node;
use Moose;
has [qw/parent child/] => (is => 'ro', isa => 'Node');
package main;
my $a = Node->new;
my $b = Node->new(parent => $a);
现在如果我想让 $a->child
指向 $b
,我该怎么办?
This could seem like an obviously hopeless case, but is there a trick to create a cyclic graph of immutable objects in Perl? Something like this:
package Node;
use Moose;
has [qw/parent child/] => (is => 'ro', isa => 'Node');
package main;
my $a = Node->new;
my $b = Node->new(parent => $a);
Now if I wanted $a->child
to point to $b
, what can I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用延迟初始化来玩游戏:
动态生成构建器和谓词:
这允许
其输出为
使用 η-conversion,但 Moose 不会将参数传递给构建器方法。
You could play games with lazy initialization:
Generate the builders and predicates on the fly:
This allows
Its output is
The code could be more elegant with η-conversion, but Moose won't pass parameters to builder methods.
我必须去看看真正不可变的语言是如何做类似的事情
这个,我认为以下可能是一个合理的尝试。
基本上,您不必尝试单独构建对象,而是
父级根据传入的参数自动激活子级。这
其输出是,我相信这是您想要的结构。
I had to go and look at how really immutable languages do something like
this, and I think the following is probably a reasonable attempt.
Basically instead of trying to build the objects separately, you have
the parent auto-vivify the child based on passing in it's arguments. The
output for this is, which is I believe the structure you were wanting.
我对 Moose 还很陌生,但是触发器有用吗?
I'm still very new to Moose, but would a trigger work?