Skip to content

Commit

Permalink
Initial version of Seq.sort . Seems to have issues with
Browse files Browse the repository at this point in the history
arity-1 blocks; working on those a bit more.
  • Loading branch information
pmichaud committed Feb 23, 2010
1 parent 4071ac3 commit 069df7a
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/core/Seq.pm
Expand Up @@ -4,6 +4,36 @@ augment class Seq {
method Str() {
pir::join(' ', self!fill);
}

multi method sort(&by = pir::get_hll_global__Ps('&infix:<cmp>')) {
# Parrot already provides a sort method that works on
# ResizablePMCArray, so we aim to make use of that here.
# Instead of sorting the elements directly, we sort an RPA
# of indices, then use that RPA as a slice into self.

# If &by.arity < 2, then it represents a block to be applied
# to the elements to obtain the values for sorting.
my ($list, &cmp);
if (&by.?arity // 2) < 2 {
$list = self.map(&by);
&cmp = pir::get_hll_global__Ps('&infix:<cmp>');
}
else {
$list = self.eager;
&cmp = &by;
}

# Now we sort the list. We create a RPA (Parcel) list of
# indices from 0 to $list.elems - 1, sort those using
# RPA.sort and &cmp, and slice the result. (If &cmp
# indicates two elements are equal, we use the indices
# for the comparison, producing a stable sort.)
self[
(^pir::elements($list)).eager.sort(
-> $a, $b { &cmp($list[$a], $list[$b]) || $a <=> $b }
)
];
}
}

# vim: ft=perl6

0 comments on commit 069df7a

Please sign in to comment.