Documentation for syntax gather take
assembled from the following pages:
Language documentation: Control flow §
From Control flow
(Control flow) Control flow gather take gather take §
gather
is a statement or block prefix that returns a sequence of values. The values come from calls to take in the dynamic scope of the gather
block. In the following example, we implement a subroutine to compute the factors of an integer with gather
(note that the factors are not generated in a strictly increasing order):
sub factors( Int \n ) say factors(36); # OUTPUT: «1, 36, 2, 18, 3, 12, 4, 9, 6»
The gather/take
combination can generate values lazily, depending on context. If you want to force lazy evaluation use the lazy subroutine or method. Binding to a scalar or sigilless container will also force laziness. For example:
my = lazy gather say [0];say 'between consumption of two values';say [1]; # OUTPUT: # 1 # between consumption of two values # Produced a value # 2
gather/take
is scoped dynamically, so you can call take
from subs or methods that are called from within gather
:
sub weird(, : = 'forward') say weird(<a b c>, :direction<backward> ); # OUTPUT: «(c b a)»
If values need to be mutable on the caller side, use take-rw.
Note that gather/take
also work for hashes. The return value is still a Seq
but the assignment to a hash in the following example makes it a hash.
my = gather ;say ; # OUTPUT: «{bar => 2, foo => 1}»