Course of Raku / Advanced /
Control flow / gather and
take / Exercises / Repeat each
number
Solution: Repeat each number
Here is a possible solution to the task.
Code
my @result = gather for 1..4 -> $n {
take $n for 1..$n;
};
say @result;🦋 You can find the source code in the file collect-the-evens.raku.
Output
[1 2 2 3 3 3 4 4 4 4]Comments
Nothing forces a single
takeper iteration. Here the innertake $n for 1..$nrunstakea different number of times on each pass, which is exactly the flexibility that makesgather/takemore powerful than a plainmap.The outer loop uses a named variable
-> $non purpose. If we wrote the inner loop with$_, the innerforwould rebind$_to its own counter, and we would take the counter instead of the current number.gathersimply collects every value that was taken, in order, so@resultends up holding1, then two2s, then three3s, then four4s.
Course navigation
← Repeat each number | Squares →