Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why no "each" method on Perl6 sequences?

Tags:

raku

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.

like image 319
Sean Avatar asked Oct 02 '19 18:10

Sean


2 Answers

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.

like image 74
Holli Avatar answered Oct 23 '22 23:10

Holli


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
like image 8
LuVa Avatar answered Oct 23 '22 23:10

LuVa