Skip to content
This repository
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 584 lines (455 sloc) 16.744 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
use v6;

use Test;

plan 28;

# This is a perl6 implementation of L<S29/List/"=item sort">
# based on mergesort.

=begin comment

  * Existence
     * Clarify why this implementation of a spec'ed feature
exists in the "unspecced" directory of the test suite.
* That was where suggested when asked for suggestions
on #perl6. Other suggestions welcome.

* Pugs
* `subset`

* Spec
* any Ordering has traits or only top level?
* {.TEST(:M)} is descending => &fuzzy_cmp is insensitive

* Syntax cleanup
* guidance on making this the builtin sort()

=end comment

# L<S29/"List"/"=item sort">

my $prelude_sort = q:to 'END_PRELUDE_SORT';
subset KeyExtractor of Code where { .sig === :(Any --> Any) };
subset Comparator of Code where { .sig === :(Any, Any --> Int) };
subset OrderingPair
of Pair where { .key ~~ KeyExtractor && .value ~~ Comparator };
subset Ordering
of Signature | KeyExtractor | Comparator | OrderingPair;

module Prelude::Sort {
our Order
sub qby_cmp (Code @qby, $a, $b)
{
my $result = Order::Same;
my &return_ifn0 ::= -> $v { if $v { $result = $v; leave LOOP; } };

LOOP: for @by -> $cmpr {
return_ifn0 $cmpr($a, $b);
}

$result;
}

our bool
sub in_order (Code @qby, *$x, *@xs)
{
my $result = 1;
my $y := $x;

for @xs -> $z {
if by_cmp(@qby, $y, $z) > 0 {
$result = 0;
last;
}

$y := $z;
}

$result;
}

our Array of Code
sub qualify_by (Ordering @by)
{
my Any sub keyex (KeyExtractor $ex, Any $v) is cached
{ $ex($v); }

my Array sub sigkex (Signature $sig is copy, Any $v) is cached
{ $sig := $v; @$sig; }

gather {
for @by -> $criterion {
when Signature {
my Signature $sig := $crierion;
my Array &kex := &sigkex;

my $cmpr -> $a, $b {
my $value;

for zip(@$a; @$b; @$sig) -> $x, $y, ::T {
my $u;
my $v;

if ( ::T ~~ canonicalized ) {
$u = ::T.canonicalized.($x);
$v = ::T.canonicalized.($y);
}
else {
$u := $x;
$v := $y;
}

last if $value = $u cmp $v;
}

$value;
}

if ( $sig ~~ descending ) {
$cmpr = -> $a, $b { $cmpr($b, $a) };
}

take( -> $a, $b {
$cmpr(kex($sig, $a), kex($sig, $b))
});
}

when KeyExtractor {
my KeyExtractor $ex := $criterion;
my &kex := &keyex;

my $cmpr = &cmp;

if ( $ex ~~ canonicalized ) {
$cmpr = -> $a is copy, $b is copy {
$a = $ex.canonicalized.($a);
$b = $ex.canonicalized.($b);
$cmpr($a, $b)
};
}

if ( $ex ~~ descending ) {
$cmpr = -> $a, $b { $cmpr($b, $a) };
}

take( -> $a, $b { $cmpr(kex($ex, $a), kex($ex, $b)) } );
}

when Comparator {
my Comparator $cmpr = $criterion;

if ( $criterion ~~ insensitive ) {
$cmpr = -> $a, $b {
$a = $criterion.canonicalized.($a);
$b = $criterion.canonicalized.($b);
$cmpr($a, $b)
};
}

if ( $criterion ~~ descending ) {
$cmpr = -> $a, $b { $cmpr($b, $a) };
}

take($cmpr);
}

when Pair {
my OrderingPair $scp := $criterion;
my &kex := &keyex;

my KeyExtractor $ex = $scp.key;
my Comparator $cmpr = $scp.value;

if ( $pair ~~ canonicalized ) {
$cmpr = -> $a, $b {
$a = $pair.canonicalized.($a);
$b = $pair.canonicalized.($b);
$cmpr($a, $b)
};
}

if ( $pair ~~ descending ) {
$cmpr = -> $a, $b { $cmpr($b, $a) };
}

take( -> $a, $b { $cmpr(kex($ex, $a), kex($ex, $b)) } );
}
}
}
}

# mergesort() --
# O(N*log(N)) time
# O(N*log(N)) space
# stable

our Array
sub mergesort (@values is rw, Ordering @by? = list(&infix:<cmp>),
Bit $inplace?)
{
my @result;

my @qby = qualify_by(@by);

if $inplace {
inplace_mergesort(@values, 0 => +@values, @qby);
@result := @values;
}
else {
my @copy = @values;
inplace_mergesort(@copy, 0 => +@copy, @qby);
@result := @copy;
}

@result;
}

our Pair
sub inplace_mergesort (@values is rw, Pair $span, Code @qby)
{
my $result = $span;

unless ( $span.value - $span.key == 1 || in_order(@qby, @values) ) {
my $mid = $span.key + int( ($span.value - $span.key)/ 2 );

$result = merge(
@values,
inplace_mergesort(@values, $span.key => $mid, @qby),
inplace_mergesort(@values, $mid => $span.value, @qby),
@qby
);
}

$result;
}

our Pair
sub merge (@values is rw, Pair $lspan, Pair $rspan, Code @qby)
{
# copy @left to a scratch area
my @scratch = @values[$lspan.key ..^ $lspan.value];

# merge @scratch and @right into and until @left is full
my $lc = $lspan.key;
my $rc = $rspan.key;
my $sc = 0;

while ( $lc < $lspan.value ) {
@values[$lc++] = by_cmp(@qby, @scratch[$sc], @values[$rc]) <= 0
?? @scratch[$sc++]
!! @values[$rc++];
}

# at this point @left is full. start populating @right
# until @scratch or @right is empty
my $ri = $rspan.key;

while ( $sc < +@scratch && $rc < $rspan.value ) {
@values[$ri++] = by_cmp(@qby, @scratch[$sc], @values[$rc]) <= 0
?? @scratch[$sc++]
!! @values[$rc++];
}

# anything remaining in @right is in the correct place.
# anything remaining in @scratch needs to be filled into @right
@values[$ri..^$rspan.value] = @scratch[$sc..^+@scratch];

# return the merged span
$lspan.key => $rspan.value;
}
}

our Array multi Array::p6sort( @values is rw, *&by, Bit $inplace? )
{
Prelude::Sort::mergesort(@values, list(&by), $inplace);
}

our Array multi Array::p6sort( @values is rw, Ordering @by, Bit $inplace? )
{
Prelude::Sort::mergesort(@values, @by, $inplace);
}

our Array multi Array::p6sort( @values is rw, Ordering $by = &infix:<cmp>,
Bit $inplace? )
{
Array::sort(@values, $by, $inplace);
}

our List multi List::p6sort( Ordering @by, *@values )
{
my @result = Prelude::Sort::mergesort(@values, @by);
@result[];
}

our List multi List::p6sort( Ordering $by = &infix:<cmp>, *@values )
{
my @result = Prelude::Sort::mergesort(@values, list($by));
@result[];
}
END_PRELUDE_SORT

ok(eval($prelude_sort), 'prelude sort parses', :todo<sort>,
:depends<subset and argument list return signatures>);

## tests

## sample() -- return a random sample of the input
sub sample (:$count, :$resample, *@data)
{
my $max = $count ?? $count !! +@data;

return gather {
if ! ( $resample ) {
my @copy = @data;

loop (my $i = 0; $i < $max; ++$i ) {
take @copy.splice((1..+@copy).pick, 1);
}
}
else {
loop (my $i = 0; $i < $max; ++$i ) {
take @data[(1..+@data).pick];
}
}
}
}

my @num = sample 1..26;
my @str = sample 'a'..'z';
my @num_as_str = sample( '' >>~<< @num);

my @sorted_num = 1..26;
my @sorted_str = 'a'..'z';
my @sorted_num_as_str =
<1 10 11 12 13 14 15 16 17 18 19 2 20 21 22 23 24 25 26 3 4 5 6 7 8 9>;

class Thingy {
has $.name;
}

my @sorted_things = map { Thingy.new( :name($_) ) },
( reverse('N'..'Z'), reverse('a'..'m') );

my @unsorted_things = sample(@sorted_things);

{
my @sorted;
ok(eval('@sorted = p6sort @str;'), 'parse of p6sort',
:todo<feature>);

ok(@sorted eqv @sorted_str, 'string ascending; default cmp',
:todo, :depends<p6sort>);
}

{
my @sorted;
ok(eval('@sorted = p6sort { $^a <=> $^b }, @num;'), 'parse of p6sort',
:todo<feature>);

ok(@sorted eqv @sorted_num, 'number ascending; Comparator',
:todo, :depends<p6sort>);
}

{
my @sorted;
ok(eval('@sorted = p6sort { lc $^b.name cmp lc $^a.name }, @unsorted_things;'),
'parse of p6sort', :todo<feature>);

ok(@sorted eqv reverse(@sorted_things), 'string descending; Comparator',
:todo, :depends<p6sort>);
}

{
my @sorted;
ok(eval('@sorted = p6sort { $^b.name cmp $^a.name } is insensitive, @str;'),
'parse trait on block closure',
:todo<feature>,
:depends<traits on block closures>);


ok(@sorted eqv reverse(@sorted_str),
'string descending; Comparator is insensitive',
:todo, :depends<p6sort>);
}

{
my @sorted;
ok(eval('@sorted = p6sort { $^a.name cmp $^b.name } is descending is insensitive, @str;'),
'parse trait on block closure',
:todo<feature>,
:depends<traits on block closures>);

ok(@sorted eqv reverse(@sorted_str),
'string descending; Comparator is descending is insensitive',
:todo, :depends<p6sort>);
}

# TODO: Modtimewise numerically ascending...
#
# my @files = sample { ... };
# my @sorted_files = qx( ls -t @files[] );

{
# my @sorted = p6sort { $^a.:M <=> $^b.:M }, @files;
#
# ok(@sorted eqv @sorted_files, 'number ascending; Comparator',
# :todo<sort>);

}

sub fuzzy_cmp($x, $y) returns Int
{
if ( 10 >= $x < 20 && 10 >= $y < 20 ) {
return $y <=> $x;
}

return $x <=> $y;
}

{
my @answer = 5..9, reverse(10..19), 20..24;
my @unsorted = sample(@answer);

my @sorted;
ok(eval('@sorted = p6sort &fuzzy_cmp, @unsorted;'),
'parse of p6sort', :todo<feature>);

ok(@sorted eqv @answer, 'number fuzzy; Comparator', :todo,
:depends<sort>);
}

{
my @sorted;
ok(eval('@sorted = p6sort { + $^elem }, @num_as_str;'),
'parse of p6sort', :todo<feature>);

ok(@sorted eqv @sorted_num,
'number ascending; KeyExtractor uses context',
:todo, :depends<p6sort>);

ok(eval('@sorted = p6sort { + $_ }, @num_as_str;'),
'parse of p6sort', :todo<feature>);

ok(@sorted eqv @sorted_num,
'number ascending; KeyExtractor uses $_',
:todo, :depends<p6sort>);
}

class Thingy {
has $.name;
}

my @sorted_things = map { Thingy.new( :name($_) ) },
( reverse('N'..'Z'), reverse('a'..'m') );

my @unsorted_things = sample(@sorted_things);

{
my @sorted;
ok(eval('@sorted = p6sort { ~ $^elem.name } is descending is insensitive, @unsorted_things;'),
'parse trait on block closure',
:todo<feature>,
:depends<traits on block closures>);

ok(@sorted eqv @sorted_things,
'string descending; KeyExtractor is descending is insensitive',
:todo, :depends<p6sort>);

ok(eval('@sorted = p6sort { lc $^elem.name } is descending, @unsorted_things;'),
'parse trait on block closure',
:todo<feature>,
:depends<traits on block closures>);

ok(@sorted eqv @sorted_things,
'string descending; KeyExtractor is descending uses context',
:todo, :depends<p6sort>);

ok(eval('@sorted = p6sort { lc .name } is descending, @unsorted_things;'),
'parse trait on block closure',
:todo<feature>,
:depends<traits on block closures>);

ok(@sorted eqv @sorted_things,
'string descending; KeyExtractor is descending uses dot',
:todo, :depends<p6sort>);
}

{
# my @sorted = p6sort { .:M } @files;
#
# ok(@sorted eqv @sorted_files, 'number ascending; KeyExtractor',
# :todo<sort>);
}

sub get_key ($elem) { return $elem.name; }

{
my @sorted;
ok(eval('@sorted = p6sort &get_key, @unsorted_things;'),
'parse of p6sort', :todo<feature>);

ok(@sorted eqv @sorted_things,
'string ascending; KeyExtractor via sub',
:todo, :depends<p6sort>);
}

my @numstr = sample( 1..3, 'A'..'C', 'x'..'z', 10..12 );
my @sorted_di_numstr = list(<z y x>, <C B A>, reverse(1..3, 10..12)),

{
my @sorted;

# Not sure you can have traits on objects but
# L<S29/List/=item sort>
# says that any Ordering can have `descending` and `canonicalized($how)` traits.
ok(eval('@sorted = p6sort ( { $_ } => {
        given $^a {
            when Num {
                given $^b {
                    when Num { $^a <=> $^b }
                    default { $^a cmp $^b }
                }
            }
            default { $^a cmp $^b }
        }
        }) is descending is canonicalized({$^v ~~ Str ?? lc($v) !! $v}),
        @numstr;'),
'parse trait on object',
:todo<feature>,
:depends<traits on objects>);

ok(@sorted eqv @sorted_di_numstr,
'Num|Str fuzzy; Pair is descending is insensitive',
:todo, :depends<p6sort>);

# @sorted = p6sort { $_ ~~ :M } => { $^b cmp $^a }, @files;
#
# ok(@sorted eqv @sorted_modtime_cmp_files,
# 'string descending; Pair uses cmp',
# :todo<sort>);
#
# @sorted = p6sort { $_ ~~ :M } => &fuzzy_cmp, @files;
#
# ok(@sorted eqv @sorted_modtime_fuzzy_files,
# 'number fuzzy; Pair',
# :todo<sort>);
#
# @sorted = p6sort ( { $_ ~~ :M } => { $^a cmp $^b } ) is descending, @files;
#
# ok(@sorted eqv @sorted_modtime_cmp_files,
# 'string descending; Pair is descending',
# :todo<sort>);
}

{
# Need to think about this one to create a meaningful dataset.
#
# # Numerically ascending
# # or else namewise stringifically descending case-insensitive
# # or else modtimewise numerically ascending
# # or else namewise fuzz-ifically
# # or else fuzz-ifically...
# @sorted = p6sort [ {+ $^elem},
# {$^b.name cmp $^a.name} is insensitive,
# {.TEST(:M)},
# {.name}=>&fuzzy_cmp,
# &fuzzy_cmp,
# ],
# @unsorted;
#
# ok(@sorted eqv @sorted_whacky, 'obj whacky; @by', :todo<sort>);
}

my @inplace = @str;

{
ok(@inplace !eqv @sorted_str, 'sampled data differs from answer');

ok(eval('@inplace.p6sort(:inplace);', 'parse of p6sort with optional $inplace'),
:todo<feature>);

ok(@inplace eqv @sorted_str, 'inplace sort on array', :todo,
        :depends<p6sort>);
}
Something went wrong with that request. Please try again.