Subject: | wishlist: partition function |
I know this is just spitting in the wind unless I JFDI, but I had a thought in passing so I wanted to jot it down here so it isn't forgotten.
A 'partition' function would be useful, to divide a list into 2 or more lists according to some condition. It is fairly straightforward to implement this in terms of 'reduce', but it would no doubt be faster if it was done directly in XS. Here is the reduce implementation (where the provided sub returns the index to use for the destination lists):
sub partition (&@) {
my $sub = shift;
my $results = reduce {
push @{ $a->[$sub->($b)] }, $b;
$a;
} [ [], [] ], @_;
return @$results;
}
e.g. partition(sub { $_[0] % 2 }, 0..10) yields the result:
[
0,
2,
4,
6,
8,
10
],
[
1,
3,
5,
7,
9
],