Skip to content

Commit a8e3008

Browse files
committed
#926 produce method is not documented
Add documentation for produce based on reduce
1 parent c2ecacb commit a8e3008

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

doc/Type/List.pod6

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -728,6 +728,63 @@ https://en.wikipedia.org/wiki/Fold_%28higher-order_function%29#Folds_on_lists>.
728728
With a right-associative operator it is a right fold, otherwise (and usually)
729729
it is a left fold.
730730
731+
=head2 routine produce
732+
733+
Defined as:
734+
735+
multi sub produce(&with, *@values)
736+
multi method produce(List:D: &with)
737+
738+
Generates a list of all intermediate "combined" values along with the final
739+
result by iteratively applying a function which knows how to combine I<two>
740+
values.
741+
742+
If C<@values> contains just a single element, a list containing that element
743+
is returned immediately. If it contains no elements, an exception is thrown,
744+
unless C<&with> is an I<operator> with a known identity value.
745+
746+
If C<&with> is the function object of an I<operator>, its
747+
inherent identity value and associativity is respected - in other words,
748+
C<(VAL1, VAL2, VAL3).produce(&[OP])> is the same as C<VAL1 OP VAL2 OP VAL3> even
749+
for operators which aren't left-associative:
750+
751+
# Raise 2 to the 81st power, because 3 to the 4th power is 81
752+
[2,3,4].produce(&[**]).say; # (4 81 2417851639229258349412352)
753+
say produce &[**], (2,3,4); # (4 81 2417851639229258349412352)
754+
say [\**] (2,3,4); # (4 81 2417851639229258349412352)
755+
756+
# Subtract 4 from -1, because 2 minus 3 is -1
757+
[2,3,4].produce(&[-]).say; # (2 -1 -5)
758+
say produce &[-], (2,3,4); # (2 -1 -5)
759+
say [\-] (2,3,4); # (2 -1 -5)
760+
761+
A triangle meta-operator C<[\ ]> provides a syntactic shortcut for
762+
producing with an infix operator:
763+
764+
# The following all do the same thing...
765+
my @numbers = (1,2,3,4,5);
766+
say produce { $^a + $^b }, 0, |@numbers;
767+
say produce * + *, 0, |@numbers;
768+
say produce &[+], @numbers; # operator does not need explicit identity
769+
say [\+] @numbers; # most people write it this way
770+
771+
The visual picture of a triangle C<[\> is not accidental. To produce a
772+
triangular list of of lists, you can use a "triangular comma":
773+
774+
[\,] 1..5
775+
(
776+
(1)
777+
(1 2)
778+
(1 2 3)
779+
(1 2 3 4)
780+
(1 2 3 4 5)
781+
)
782+
783+
Since C<produce> is an implicit loop, it responds to C<next>, C<last> and
784+
C<redo> statements inside C<&with>:
785+
786+
say (2,3,4,5).produce: { last if $^a > 7; $^a + $^b }; # says (2 5 9)
787+
731788
=head2 routine combinations
732789
733790
Defined as:

0 commit comments

Comments
 (0)