How to do something functionally with all the elements of a list in Perl 6?

  • A+

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 Trues), which I don't want:

>{ 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 


  • the syntax is a bit clumsy (probably I don't do it as supposed)
  • what if I don't want it to work with 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 {$_**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:{ 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{ 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) {{ put $_**2 }) } 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: