Last active
September 27, 2015 22:32
-
-
Save BenGoldberg1/2062cc4b4eda289b180a to your computer and use it in GitHub Desktop.
One-Pass Sorting Algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl6 | |
use v6; | |
sub sort-promise ($in, $out) { | |
start { | |
my @same; | |
earliest $in { | |
more * { push @same, $in.receive } | |
done * { return } | |
} | |
my ($less_c, $more_c) = Channel.new xx 2; | |
my ($less_p, $more_p) = map { sort-promise($_, $out) }, $less_c, $more_c; | |
1 while do earliest $in { | |
more * { | |
given $_ <=> @same[0] { | |
when Same { push @same, $_ } | |
when Less { $less_c.send( $_ ) } | |
when More { $more_c.send( $_ ) } | |
} | |
True; | |
} | |
done * { False } | |
}; | |
$less_c.close; $less_p.result; | |
$out.send for @same; | |
$more_c.close; $more_p.result; | |
} | |
} | |
my ($unsorted, $sorted) = Channel.new xx 2; | |
my $p = sort-promise( $unsorted, $sorted ).then({ $sorted.closed }); | |
await $p, start { | |
1 while do earliest $sorted { | |
more * { .say; } | |
done * { False } | |
}, start { | |
$unsorted.send(rand) for 1..20; | |
$unsorted.close; | |
}; | |
}; | |
say 'done'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment