my $add-mix = (foo => 0.22, bar => -0.1).Mix;
my $dim-mix;
for ^5 {
$dim-mix (+)= $add-mix;
}
dd $dim-mix; # Mix $dim-mix = ("foo"=>1.1,"bar"=>-0.5).Mix
Obviously I've not used a MixHash
, but you can sort that out if you need to after the loop.
(And of course you might be thinking "but isn't a Mix
immutable?" It is -- but you have to distinguish variables and values. $dim-mix
is a variable, a Scalar
variable. Even if you type it -- my Mix $dim-mix;
it's still a Scalar
variable holding a Mix
value. You can always assign to a Scalar
.)
I'm starting to get a routine for questions like this where I don't know what's going on but I think I ought to be able to figure it out. Here was my process:
I got your code to run to see what it did. I tried to simplify the ternary. Hmm.
I turned to the doc. There was the doc page for (+)
. That called it "Baggy addition". That was worrisome given that a Bag
only holds (positive) integers.
I turned to the source. I fired off a search of the rakudo sources for "Baggy addition". One result. I focused on the multi with (Mixy:D $a, QuantHash:D $b)
signature. This showed me that the result should stay Mixy
, i.e. the doc's implication it would or could go Baggy
is a red herring.
I returned to the code and started wondering what I could do. When I initially tried to use (+)=
to simplify the main assignment the compiler complained expected MixHash but got Mix
. I tried a half dozen things that didn't work then just changed the MixHash
constraint on $dim-mix
to Mixy
and it worked.
Then I thought through what was going on and realized that almost all the types were getting in the way of P6 just doing the right thing.
You can add some types back in if you really need them.
(But do you really need them? When types are absolutely necessary they're great. Otherwise, imo, think twice, and then twice again, before introducing them. They can easily make code harder to read, reason about, compose, and slower.)
(Of course there are occasions on which they're not strictly necessary but do really help overall. Imo, as with all things, keep it simple at first and only complexify if you see clear benefits for a particular line of code.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…