From a28cded46b46edf628ab904918b5e407c4c63e95 Mon Sep 17 00:00:00 2001 From: Solomon Foster Date: Wed, 29 Dec 2010 11:13:29 -0500 Subject: [PATCH] Allow a comparison function to be passed to sorted-merge. --- lib/List/Utils.pm | 4 ++-- t/06-sorted-merge.t | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/lib/List/Utils.pm b/lib/List/Utils.pm index 251aafb..3d35d40 100644 --- a/lib/List/Utils.pm +++ b/lib/List/Utils.pm @@ -120,7 +120,7 @@ sub upper-bound(@x, $key) is export(:DEFAULT) { return $first; } -sub sorted-merge(@a, @b) is export(:DEFAULT) { +sub sorted-merge(@a, @b, &by = &infix:) is export(:DEFAULT) { my $a-list = @a.iterator.list; my $b-list = @b.iterator.list; @@ -128,7 +128,7 @@ sub sorted-merge(@a, @b) is export(:DEFAULT) { my $b = $b-list.shift; gather loop { if $a.defined && $b.defined { - if $a before $b { + if &by($a, $b) == -1 { my $temp = $a; take $temp; $a = $a-list.shift; diff --git a/t/06-sorted-merge.t b/t/06-sorted-merge.t index d3e0fff..b119203 100644 --- a/t/06-sorted-merge.t +++ b/t/06-sorted-merge.t @@ -36,5 +36,25 @@ plan *; "sorted-merge correct with infinite lazy lists, 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"; +} + +{ + my @a := 1, * * -1/2 ... *; + my @b := 1, 1/3, 1/9 ... *; + is ~sorted-merge(@a, @b, -> $a, $b { $b.abs <=> $a.abs })[^7].perl, + (1, 1, -1/2, 1/3, 1/4, -1/8, 1/9).perl, + "sorted-merge correct with custom comparison"; + is ~sorted-merge(@b, @a, -> $a, $b { $b.abs <=> $a.abs })[^7].perl, + (1, 1, -1/2, 1/3, 1/4, -1/8, 1/9).perl, + "sorted-merge correct with custom comparison, order swapped"; +} + done_testing; \ No newline at end of file