Skip to content

Commit 80689f3

Browse files
committed
[operators] sequence op
1 parent adc0bd7 commit 80689f3

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

lib/operators.pod

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -980,4 +980,63 @@ list:
980980
'2a9', '2b9', '2c9',
981981
'3a9', '3b9', '3c9'
982982
983+
=head2 infix ...
984+
985+
multi sub infix:<...>(**@) is assoc<list>
986+
multi sub infix:<...^>(**@) is assoc<list>
987+
988+
The sequence operator is a generic operator to produce lazy lists.
989+
990+
It can have initial elements and a generator on left-hand side, and an
991+
endpoint on the right-hand side.
992+
993+
The sequence operator invokes the generator with as many arguments as
994+
necessary. The arguments are taken from the initial elements and the already
995+
generated elements.
996+
997+
The default generator is C<*.>L<succ> or C<*.>L<pred>, depending on how
998+
the end points compare:
999+
1000+
say 1 ... 4; # 1 2 3 4
1001+
say 4 ... 1; # 4 3 2 1
1002+
say 'a' ... 'e'; # a b c d e
1003+
say 'e' ... 'a'; # e d c b a
1004+
1005+
An endpoint of C<*> (L<Whatever> generates an infinite sequence,
1006+
with a default generator of *.succ
1007+
1008+
say (1 ... *)[^5]; # 1 2 3 4 5
1009+
1010+
1011+
Custom generators are the last argument before the '...' operator.
1012+
This one takes two arguments, and generates the Fibonacci numbers
1013+
1014+
say (1, 1, -> $a, $b { $a + $b } ... *)[^8]; # 1 1 2 3 5 8 13 21
1015+
# same but shorter
1016+
say (1, 1, *+* ... *)[^8]; # 1 1 2 3 5 8 13 21
1017+
1018+
Of course the generator can also take only one argument.
1019+
1020+
say 5, { $_ * 2 } ... 40; # 5 10 20 40
1021+
1022+
There must be at least as many initial elements as arguments to the generator.
1023+
1024+
Without a generator, and more than one initial element, and all initial
1025+
elements numeric, the sequence operator tries to deduce the generator. It
1026+
knows about arithmetic and geometric sequences.
1027+
1028+
say 2, 4, 6 ... 12; # 2 4 6 8 10 12
1029+
say 1, 2, 4 ... 32; # 1 2 4 8 16 32
1030+
1031+
If the endpoint is not C<*>, it is smart-matched against each generated
1032+
element, and the sequence is terminated when the smart-match succeeded.
1033+
For the C<...> operator, the final element is included, for the C<...^>
1034+
operator it is excluded.
1035+
1036+
This allows you to write
1037+
1038+
say 1, 1, *+* ...^ *>= 100;
1039+
1040+
To generate all Fibonacci numbers up to but excluding 100.
1041+
9831042
=end pod

0 commit comments

Comments
 (0)