Sean
Sean

Reputation: 29772

Why no "each" method on Perl6 sequences?

Sometimes I'll start writing a chain of method calls at the Perl 6 REPL, like:

".".IO.dir.grep(...).map(...).

...and then I realize that what I want to do with the final list is print every element on its own line. I would expect sequences to have something like an each method so I could end the chain with .each(*.say), but there's no method like that that I can find. Instead I have to return to the beginning of the line and prepend .say for. It feels like it breaks up the flow of my thoughts.

It's a minor annoyance, but it strikes me as such a glaring omission that I wonder if I'm missing some easy alternative. The only ones I can think of are ».say and .join("\n").say, but the former can operate on the elements out of order (if I understand correctly) and the latter constructs a single string which could be problematically large, depending on the input list.

Upvotes: 14

Views: 328

Answers (2)

Holli
Holli

Reputation: 5072

You can roll your own.

use MONKEY;

augment class Any 
{ 
    method each( &block )
    {
        for self -> $value { 
            &block( $value );
        }
    }
};

List.^compose;
Seq.^compose;

(1, 2).each({ .say });
(2, 3).map(* + 1).each({ .say });

# 1
# 2
# 3
# 4

If you like this, there's your First CPAN module opportunity right there.

Upvotes: 11

LuVa
LuVa

Reputation: 2288

As you wrote in the comment, just an other .map(*.say) does also create a line with True values when using REPL. You can try to call .sink method after the last map statement.

".".IO.dir.grep({$_.contains('e')}).map(*.uc).map(*.say).sink

Upvotes: 8

Related Questions