Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the first occurence of 1-digit number in a list in Raku

Tags:

list

raku

I've got a number of lists of various lengths. Each of the lists starts with some numbers which are multiple digits but ends up with a recurring 1-digit number. For instance:

my @d = <751932 512775 64440 59994 9992 3799 423 2 2 2 2>;
my @e = <3750 3177 4536 4545 686 3 3 3>;

I'd like to find the position of the first occurence of the 1-digit number (for @d 7 and for @e 5) without constructing any loop. Ideally a lambda (or any other practical thing) should iterate over the list using a condition such as $_.chars == 1 and as soon as the condition is fulfilled it should stop and return the position. Instead of returing the position, it might as well return the list up until the 1-digit number; changes and improvisations are welcome. How to do it?

like image 888
Lars Malmsteen Avatar asked Sep 06 '20 19:09

Lars Malmsteen


1 Answers

You want the :k modifier on first:

say @d.first( *.chars == 1, :k ) # 7
say @e.first( *.chars == 1, :k ) # 5

See first for more information.

To answer your second part of the question:

say @d[^$_] with @d.first( *.chars == 1, :k );
# (751932 512775 64440 59994 9992 3799 423)
say @e[^$_] with @e.first( *.chars == 1, :k );
# (3750 3177 4536 4545 686)

Make sure that you use the with to ensure you only show the slice if first actually found an entry.

See with for more information.

like image 134
Elizabeth Mattijsen Avatar answered Sep 18 '22 15:09

Elizabeth Mattijsen