Course of Raku / Advanced /
Control flow / gather and
take / Exercises / Gather until
full
Solution: Gather until full
Here is a possible solution to the task.
Code
my $sum = 0;
my @result = gather for 1..100 {
$sum += $_;
last if $sum > 10;
take $_;
}
say @result;🦋 You can find the source code in the file gather-big.raku.
Output
[1 2 3 4]Comments
The loop is given a range of a hundred numbers, far more than it will use. That is fine because the loop stops itself: as soon as
$sumpasses10,lastbreaks out and the remaining numbers are never visited.The order inside the block matters. We add to
$sumfirst and check the limit before taking, so the number that tips the total over10(here,5) is not collected. The running total reaches exactly10after4, so the gathered list is1, 2, 3, 4.This early exit with
foris whatgather/takecan do andgrepcannot:grepalways scans the whole list, while here we choose when to stop.