Permalink
Browse files

Add sorted-merge, plus basic tests.

  • Loading branch information...
1 parent 20e36bd commit cd6e59de8d376d68db5bf36addf76c7270813c4f @colomon committed Dec 29, 2010
Showing with 72 additions and 0 deletions.
  1. +32 −0 lib/List/Utils.pm
  2. +40 −0 t/06-sorted-merge.t
View
@@ -120,3 +120,35 @@ sub upper-bound(@x, $key) is export(:DEFAULT) {
return $first;
}
+sub sorted-merge(@a, @b) is export(:DEFAULT) {
+ my $a-list = @a.iterator.list;
+ my $b-list = @b.iterator.list;
+
+ my $a = $a-list.shift;
+ my $b = $b-list.shift;
+ gather loop {
+ if $a.defined && $b.defined {
+ if $a before $b {
+ my $temp = $a;
+ take $temp;
+ $a = $a-list.shift;
+ } else {
+ my $temp = $b;
+ take $temp;
+ $b = $b-list.shift;
+ }
+ } else {
+ if $a.defined {
+ my $temp = $a;
+ take $temp;
+ $a = $a-list.shift;
+ } elsif $b.defined {
+ my $temp = $b;
+ take $temp;
+ $b = $b-list.shift;
+ } else {
+ last;
+ }
+ }
+ }
+}
View
@@ -0,0 +1,40 @@
+use v6;
+use Test;
+use List::Utils;
+
+plan *;
+
+{
+ my @a = (10, 20, 20, 30);
+ my @b = 17..22;
+ is ~sorted-merge(@a, @b), ~(10,17,18,19,20,20,20,21,22,30), "Simple sorted-merge correct";
+ is ~sorted-merge(@b, @a), ~(10,17,18,19,20,20,20,21,22,30), "Simple sorted-merge correct, order swapped";
+ is ~@a, ~(10, 20, 20, 30), 'Original @a unaffected';
+ is ~@b, ~(17..22), 'Original @b unaffected';
+}
+
+{
+ my @a = 1..3;
+ my @b = 10..12;
+ is ~sorted-merge(@a, @b), ~(1, 2, 3, 10, 11, 12), "sorted-merge correct if inputs do not overlap";
+ is ~sorted-merge(@b, @a), ~(1, 2, 3, 10, 11, 12), "sorted-merge correct if inputs do not overlap, order swapped";
+}
+
+{
+ my @a = 1..3;
+ my @b;
+ is ~sorted-merge(@a, @b), ~(1, 2, 3), "sorted-merge correct if one input is empty";
+ is ~sorted-merge(@b, @a), ~(1, 2, 3), "sorted-merge correct if one input is empty, order swapped";
+}
+
+{
+ my @a := 1, 1, *+* ... *;
+ my @b := 3, 6 ... *;
+ is ~sorted-merge(@a, @b)[^10], ~(1, 1, 2, 3, 3, 5, 6, 8, 9, 12),
+ "sorted-merge correct with infinite lazy lists";
+ is ~sorted-merge(@b, @a)[^10], ~(1, 1, 2, 3, 3, 5, 6, 8, 9, 12),
+ "sorted-merge correct with infinite lazy lists, order swapped";
+}
+
+
+done_testing;

0 comments on commit cd6e59d

Please sign in to comment.