Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List repetition (xx) without evaluation?

Tags:

raku

The list repetition operator (xx) evaluates the list every time it is repeated. For example,

my @input = get() xx 5;

will evaluate to the first 5 lines of STDIN. Is there any way I can repeat just the value of the element 5 times, rather than evaluating it each time? Currently, I've been assigning it to a variable, then repeating it, but it seems a bit cumbersome that way.

my $firstLine = get();
my @firstlineRepeated = $firstLine xx 5;

Is there a prefix or something that lets me do it in one statement?

like image 962
Jo King Avatar asked Aug 09 '18 11:08

Jo King


3 Answers

Using given to contextualize it into $_ is one fairly neat way:

my @input = ($_ xx 5 given get());
say @input;

That, when I type hello, gives:

[hello hello hello hello hello]

Since given simply contextualizes, rather than doing any kind of definedness or truth test, it's a bit safer as a general pattern than andthen.

like image 182
Jonathan Worthington Avatar answered Dec 16 '22 06:12

Jonathan Worthington


You could try use the andthen operator:

my @input = (get() andthen $_ xx 5);

From the documentation:

The andthen operator returns Empty upon encountering the first undefined argument, otherwise the last argument. Last argument is returned as-is, without being checked for definedness at all. Short-circuits. The result of the left side is bound to $_ for the right side, or passed as arguments if the right side is a Callable, whose count must be 0 or 1.

like image 37
Håkon Hægland Avatar answered Dec 16 '22 08:12

Håkon Hægland


Using phrase ENTER works too

my @input = ENTER { get() } xx 5;
like image 25
wamba Avatar answered Dec 16 '22 08:12

wamba