for my project I need to build a tree structure. I am looking for a way to grow it at the leaves. I have simplified my failed attempt by using a listy structure:
my $root = a => (b => (c=> Nil));
my $here := $root;
while $here.value ~~ Pair {
$here := $here.value;
}
$here = d => Nil;
which does not work, because I cannot change Nil, of course. Cannot assign to an immutable value How can I make this work?
Thanks, Theo van den Heuvel
I think the error message you get "Cannot assign to an immutable value" is because the value is not a container. Here is an example where I make the leaf node a container:
my $root = a => (b => (my $ = (c => Nil)));
my $here := $root;
while $here.value ~~ Pair {
$here := $here.value;
}
$here = d => Nil;
Now, there is no error message.
You are using binding, not assignment for $here
my $root = a => (b => (c=> Nil));
my $here = $root;
while $here.value ~~ Pair {
$here = $here.value;
}
$here = d => Nil;
When you use bind, the left and the right-hand side are the same object. And once they are the same object, well, they can't change (if the bound object is immutable, that is). They're immutable:
my $bound := 3; $bound = 'þorn'; say $bound;
# OUTPUT: «Cannot assign to an immutable value»
3
above is immutable, so you can't assign to it. In the code you have provided, you could change the value by rebinding until you arrived to an immutable value, the last Pair
, which explains the message.
Just use ordinary assignment and you're good to go. If what you want is to keep the original value of $root
somewhere, just do this and use $root
to do the tree navigation
my $root = a => (b => (c=> Nil));
my $here = $root;
while $root.value ~~ Pair {
$root = $root.value;
}
$here = d => Nil;
say $here;
say $root;
$here
will still be equal to the original root, and $root
will have navigated to the last branch and leaf.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With