如何创建像树一样的数据结构

时间:2018-05-09 11:02:42

标签: data-structures perl6

对于我的项目,我需要构建一个树结构。我正在寻找一种在树叶上种植它的方法。我通过使用listy结构简化了失败的尝试:

my $root = a => (b => (c=> Nil));
my $here := $root;
while $here.value ~~ Pair {
  $here := $here.value;
}
$here = d => Nil;

哪个不起作用,因为我当然不能改变Nil。     无法分配给不可变值 我怎样才能做到这一点?

谢谢, Theo van den Heuvel

2 个答案:

答案 0 :(得分:3)

我认为您收到的错误消息"无法分配给不可变值" 是因为该值不是container。这是一个我将叶节点作为容器的例子:

my $root = a => (b => (my $ = (c => Nil)));
my $here := $root;
while $here.value ~~ Pair {
  $here := $here.value;
}
$here = d => Nil;

现在,没有错误消息。

答案 1 :(得分:3)

您正在使用binding,而不是$here

的作业
my $root = a => (b => (c=> Nil));
my $here = $root;
while $here.value ~~ Pair {
  $here = $here.value;
}
$here = d => Nil;

使用bind时,左侧和右侧是同一个对象。一旦它们是同一个对象,那么它们就无法改变(如果绑定的对象是不可变的,那就是)。他们是不可改变的:

my $bound := 3; $bound = 'þorn'; say $bound; 
# OUTPUT: «Cannot assign to an immutable value␤» 
上面的

3是不可变的,因此您无法分配给它。在您提供的代码中,您可以通过重新绑定来更改值,直到达到不可变值,即最后Pair,它解释了消息。

只需使用普通作业就可以了。如果你想要的是保持$root的原始值,只需执行此操作并使用$root进行树导航

my $root = a => (b => (c=> Nil));
my $here = $root;
while $root.value ~~ Pair {
  $root = $root.value;
}
$here = d => Nil;
say $here;
say $root; 

$here仍然等于原始根,$root将导航到最后一个分支和叶子。