For example I have an Array
with numbers:
> my @a = ^5
[0 1 2 3 4]
and I want to print their squares. I can use map
, but it will also return a modified List
(these five True
s), which I don't want:
> @a.map({ put $_**2 })
0
1
4
9
16
(True True True True True)
The only way I've found is to use hyper >>
:
> @a>>.&{ put $_**2 }
0
1
4
9
16
but
hyper
?So what is the right way to do it?
P.S. Of course, I can use map
and then put
the result:
.put for @a.map: {$_**2 }
but that's not what I want.
Using map
is fine for this purpose, since in sink context it will not produce a result list. In the REPL, the result of the map
is wanted, thus why it is produced. But in a case like:
@a.map({ put $_**2 });
say "That's all, folks";
Then the result of the map
is not wanted, and so no list of results will be assembled. If wishing to really spell this out, it's possible to write:
sink @a.map({ put $_**2 })
Be aware that the last statement in a routine is taken as an implicit return value. Using --> Nil
will suffice to ensure a final map
is in sink context instead.
sub put-squares(@a --> Nil) {
@a.map({ put $_**2 })
}
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