routine sort

Documentation for routine sort, assembled from the following types:

class Any

From Any

(Any) method sort

Defined as:

multi method sort()
multi method sort(&custom-routine-to-use)

Sorts iterables with infix:<cmp> or given code object and returns a new List. Optionally, takes a Callable as a positional parameter, specifying how to sort.


say <b c a>.sort;                           # OUTPUT: «(a b c)␤» 
say 'bca'.comb.sort.join;                   # OUTPUT: «abc␤» 
say 'bca'.comb.sort({$^b cmp $^a}).join;    # OUTPUT: «cba␤» 
say '231'.comb.sort(&infix:«<=>»).join;     # OUTPUT: «123␤» 

class List

From List

(List) routine sort

Defined as:

multi sub    sort(*@elems      --> Seq:D)
multi sub    sort(&custom-routine-to-use*@elems --> Seq:D)
multi method sort(List:D:      --> Seq:D)
multi method sort(List:D: &custom-routine-to-use  --> Seq:D)

Sorts the list, smallest element first. By default infix:<cmp> is used for comparing list elements.

If &custom-routine-to-use is provided, and it accepts two arguments, it is invoked for pairs of list elements, and should return Order::Less, Order::Same or Order::More.

If &custom-routine-to-use accepts only one argument, the list elements are sorted according to custom-routine-to-use($a) cmp custom-routine-to-use($b) . The return values of &custom-routine-to-use are cached, so that &custom-routine-to-use is only called once per list element.


say (3-47-120).sort;                  # OUTPUT: «(-4 -1 0 2 3 7)␤» 
say (3-47-120).sort: *.abs;           # OUTPUT: «(0 -1 2 3 -4 7)␤» 
say (3-47-120).sort: { $^b leg $^a }# OUTPUT: «(7 3 2 0 -4 -1)␤» 

Additionally, if &custom-routine-to-use returns a List, elements will be sorted based upon multiple values with subsequent values in the List being used to break the tie if the comparison between the prior elements evaluate to Order::Same.

my @resistance = (
    %first-name => 'Kyle',  last-name => 'Reese'  ),
    %first-name => 'Sarah'last-name => 'Connor' ),
    %first-name => 'John',  last-name => 'Connor' ),
.say for @resistance.sort: { .<last-name>.<first-name> };
  {first-name => John, last-name => Connor}
  {first-name => Sarah, last-name => Connor}
  {first-name => Kyle, last-name => Reese}

class Supply

From Supply

(Supply) method sort

method sort(Supply:D: &custom-routine-to-use? --> Supply:D)

Taps the Supply it is called on. Once that Supply emits done, all of the values that it emitted will be sorted, and the results emitted on the returned Supply in the sorted order. Optionally accepts a comparator Block. If the original Supply quits, then the exception is immediately conveyed on the return Supply.

my $s = Supply.from-list(41032);
my $t = $s.sort();
$t.tap(&say);           # OUTPUT: «2␤3␤4␤10␤»