Skip to content

Commit

Permalink
Adds examples on multicriteria sort
Browse files Browse the repository at this point in the history
Which I understand is what's behind #1297. There was already an example, but these new ones maybe clarify it, thus closes #1297
  • Loading branch information
JJ committed Sep 7, 2018
1 parent 6988308 commit 0b11f85
Showing 1 changed file with 26 additions and 9 deletions.
35 changes: 26 additions & 9 deletions doc/Type/List.pod6
Expand Up @@ -720,22 +720,22 @@ If C<&custom-routine-to-use> is provided, and it accepts two arguments,
it is invoked for pairs of list elements, and should return
C<Order::Less>, C<Order::Same> or C<Order::More>.
If C<&custom-routine-to-use> accepts only one argument, the list elements are
sorted according to
C<< custom-routine-to-use($a) cmp custom-routine-to-use($b) >>. The return
values of C<&custom-routine-to-use> are cached, so that
C<&custom-routine-to-use> is only called once per list element.
If C<&custom-routine-to-use> accepts only one argument, the list
elements are sorted according to C<< custom-routine-to-use($a) cmp
custom-routine-to-use($b) >>. The return values of
C<&custom-routine-to-use> are cached, so that C<&custom-routine-to-use>
is only called once per list element.
Examples:
say (3, -4, 7, -1, 2, 0).sort; # OUTPUT: «(-4 -1 0 2 3 7)␤»
say (3, -4, 7, -1, 2, 0).sort: *.abs; # OUTPUT: «(0 -1 2 3 -4 7)␤»
say (3, -4, 7, -1, 2, 0).sort: { $^b leg $^a }; # OUTPUT: «(7 3 2 0 -4 -1)␤»
Additionally, if C<&custom-routine-to-use> returns a C<List>, elements will be
sorted based upon multiple values with subsequent values in the C<List> being
used to break the tie if the comparison between the prior elements evaluate to
C<Order::Same>.
Additionally, if C<&custom-routine-to-use> returns a C<List>, elements
will be sorted based upon multiple values with subsequent values in the
C<List> being used to break the tie if the comparison between the prior
elements evaluate to C<Order::Same>.
my @resistance = (
%( first-name => 'Kyle', last-name => 'Reese' ),
Expand All @@ -751,6 +751,23 @@ C<Order::Same>.
{first-name => Kyle, last-name => Reese}
)
This sorting can be based on characteristics of a single element:
=begin code
say <ddd aaa bbb bb ccc c>.sort( {.chars, .Str} );
# OUTPUT: «(c bb aaa bbb ccc ddd)␤»
=end code
In this case, elements of the array are sorted in ascending order
according first to the string length (C<.chars>) and second to the
actual alphabetical order C<.Str>) if the length is exactly the same.
Any number of criteria can be used in this:
=begin code
say <01 11 111 2 20 02>.sort( { .Int, .comb.sum, .Str } );
# OUTPUT: «(01 02 2 11 20 111)␤»
=end code
=head2 routine unique
Defined as:
Expand Down

0 comments on commit 0b11f85

Please sign in to comment.