Sorting and undefined values

Uri Guttman uri at stemsystems.com
Thu Dec 14 19:46:38 GMT 2006


>>>>> "AA" == Andy Armstrong <andy at hexten.net> writes:

  AA> On 14 Dec 2006, at 18:09, Earle Martin wrote:
  >> Read about it many times, never quite understood it; still don't feel
  >> the need to. Way too idiomatic for my tastes. Thanks, though.

  AA> It's conceptually simple: if you're sorting a bunch of items and the
  AA> value that you're comparing to determine the ordering is expensive to
  AA> compute you precompute those values and stash them along with the
  AA> things being sorted - thereby reducing the number of expensive
  AA> operations by a factor of approx log N.

for more on this read:

	http://sysarch.com/Perl/sort_paper.html

and check out Sort::Maker which can build an ST or GRT sorter for you. i
never did understand the actual sorting order desired by the OP. the
code example was broken as was pointed out. is this a single level sort
(use x OR y depending on what is defined) or sort by x first and then
sort the ties by y?

what is great about Sort::Maker is that you only need to define the key
extraction one time (not duplicating it with $a and $b) and it works on
$_ which is set to the element to be sorted. so assuming a simple use x
if defined or else y (not even checking for undef in y) it would look
something like this (untested and pseudoish):

use Sort::Maker ;

my $sorter = make_sorter(
		'ST',
		number	=> sub { defined $_->{x} ? $_->{x} : $_->{y} },
) ;

my @sorted = $sorter->( @unsorted ) ;

if you use blead perl you could reduce that to $_->{x} // $_->{y}

:)

uri

-- 
Uri Guttman  ------  uri at stemsystems.com  -------- http://www.stemsystems.com
--Perl Consulting, Stem Development, Systems Architecture, Design and Coding-
Search or Offer Perl Jobs  ----------------------------  http://jobs.perl.org


More information about the london.pm mailing list