Skip to content

Commit

Permalink
Continues with #2069, with iterating constructs
Browse files Browse the repository at this point in the history
  • Loading branch information
JJ committed May 30, 2018
1 parent 35df3e1 commit d00b646
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions doc/Language/iterating.pod6
Expand Up @@ -95,11 +95,31 @@ build an iterator type to be returned, such as we did in the previous example;
however, this example shows the minimal code needed to build a class that
fulfills the two iter(ator|able) roles.
=head1 How to iterate: contextualizing and topic variables
TBD
C<for> and other loops place the item produced in every iteration into the
L<topic variable C<$_>|/language/variables#index-entry-topic_variable>, or
capture them into the variables that are declared along with the block. These
variables can be directly used inside the loop, without needing to declare them,
by using the
L<C<^> twigil|https://docs.perl6.org/syntax/$CIRCUMFLEX_ACCENT#(Traps_to_avoid)_twigil_^>.
Implicit iteration occurs when using the L<sequence operator|/language/operators#index-entry-..._operators>.
say 1,1,1, { $^a²+2*$^b+$^c } … * > 300; # OUTPUT: «(1 1 1 4 7 16 46 127 475)
The generating block is being run once while the condition to finish the
sequence, in this case the term being bigger than 300, is not met. This has the
side effect of running a loop, but also creating a list that is output.
This can be done more systematically through the use of the L<C<gather/take>
blocks|/syntax/gather take>, which are a different kind of iterating construct
that instead of running in sink context, returns an item every iteration. This
<Advent Calendar
tutorial|https://perl6advent.wordpress.com/2009/12/23/day-23-lazy-fruits-from-the-gather-of-eden/>
explains use cases for this kind of loops; in fact, gather is not so much a
looping construct, but a statement prefix that collects the items produced by
C<take> and creates a list out of them.
=head1 C<Classic> loops and why we do not like them
Expand Down

0 comments on commit d00b646

Please sign in to comment.