Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Clarifying the dual Iterable/Iterator roles in a lazy contest refs #2139
  • Loading branch information
JJ committed Jul 3, 2018
1 parent a7691be commit b856651
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions doc/Language/list.pod6
Expand Up @@ -232,30 +232,35 @@ value, but unlike the above options, it will break L<Scalars|/type/Scalar>.
X<|laziness in iterable objects>
=head1 Lazy lists
Lists, arrays, sequences and any class with the L<Iterator> role can be lazy,
which means that their values are computed on demand and stored for later use.
To create a lazy object use L<gather/take|/language/control#gather/take> or the
L<sequence operator|/language/operators#infix_...>. You can also write a class
that implements the role L<Iterator|/type/Iterator> and returns C<True> on a
call to L<is-lazy|/routine/is-lazy>. Please note that some methods like C<elems>
cannot be called on a lazy List and will result in a thrown
C<List>s, C<Seq>s (and any class that subclasses them, like C<Array>s) and
any other class thet implements the L<Iterable> role can be lazy, which means that their
values are computed on demand and stored for later use. To create a lazy object
use L<gather/take|/language/control#gather/take> or the L<sequence
operator|/language/operators#infix_...>. You can also write a class that
implements the role L<Iterator|/type/Iterator> and returns C<True> on a call to
L<is-lazy|/routine/is-lazy>. Please note that some methods like C<elems> cannot
be called on a lazy List and will result in a thrown
L<Exception|/type/Exception>.
# This list is lazy and elements will not be available
# This array is lazy and its elements will not be available
# until explicitly requested.
my @l = lazy 1, 11, 121 ... 10**100;
say @l.is-lazy; # OUTPUT: «True␤»
say @l[]; # OUTPUT: «[...]␤»
my @lazy-array = lazy 1, 11, 121 ... 10**100;
say @lazy-array.is-lazy; # OUTPUT: «True␤»
say @lazy-array[]; # OUTPUT: «[...]␤»
# Once all elements have been retrieved, the List
# is no longer considered lazy.
my @no-longer-lazy = eager @l; # Forcing eager evaluation
my @no-longer-lazy = eager @lazy-array; # Forcing eager evaluation
say @no-longer-lazy.is-lazy; # OUTPUT: «False␤»
say @no-longer-lazy[];
# OUTPUT: (sequence starting with «[1 11 121» ending with a 300 digit number)
In the example above, C<@lazy-array> is an C<Array> which, through construction,
is make C<lazy>. When using it with C<is-lazy> it is returning an iterator,
which, since it originates in a lazy list, is itself lazy.
A common use case for lazy C<List>s is the processing of infinite sequences of
numbers, whose values have not been computed yet and cannot be computed in their
entirety. Specific values in the List will only be computed when they are
Expand Down

0 comments on commit b856651

Please sign in to comment.