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

  • A+
Category:Languages

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:

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

  • 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 @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 }) } 

Comment

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