In List§
See primary documentation in context for routine zip
sub zip(+, : --> Seq)
Builds a 'list of lists', returned as a sequence, from multiple input lists or other Iterable
s.
zip
iterates through each of the input lists synchronously, 'Zipping' them together, so that elements are grouped according to their input list index, in the order that the lists are provided.
say zip(<a b c>, <d e f>, <g h i>);# OUTPUT: «((a d g) (b e h) (c f i))»
zip
has an infix synonym, the Z
operator.
say <a b c> Z <d e f> Z <g h i>; # same output
zip
can provide input to a for loop :
for <a b c> Z <d e f> Z <g h i> -> [,,]# OUTPUT: «a,d,gb,e,hc,f,i»
, or more succinctly:
say .join(",") for zip <a b c>, <d e f>, <g h i>; # same output
Note, that if the input lists have an unequal number of elements, then zip
terminates once the shortest input list is exhausted, and trailing elements from longer input lists are discarded.
say <a b c> Z <d e f m n o p> Z <g h i>;# ((a d g) (b e h) (c f i))
In cases where data clipping is possible, but undesired, then consider using roundrobin instead of zip
.
The optional with
parameter will additionally reduce the zipped lists. For example, the following multiplies corresponding elements together to return a single list of products.
.say for zip <1 2 3>, [1, 2, 3], (1, 2, 3), :with(:<*>);# OUTPUT: «1827»
The Z
form can also be used to perform reduction by implicitly setting the with
parameter with a metaoperator :
.say for <1 2 3> Z* [1, 2, 3] Z* (1, 2, 3); # same output
In Supply§
See primary documentation in context for method zip
method zip(**, :)
Creates a supply that emits combined values as soon as there is a new value seen on all of the supplies. By default, List
s are created, but this can be changed by specifying your own combiner with the :with
parameter. The resulting supply is done as soon as any of the given supplies are done. Can also be called as a class method.
This can also be used as a class method; in case it's used as an object method the corresponding supply will be one of the supplies combined (with no special treatment).