develooper Front page | perl.perl6.language | Postings from February 2004

Re: The Sort Problem: a definitive ruling

Thread Previous | Thread Next
From:
Damian Conway
Date:
February 20, 2004 14:49
Subject:
Re: The Sort Problem: a definitive ruling
Message ID:
40368EA5.7000306@conway.org
Joe Gottman asked:

>    How do you decide whether a key-extractor block returns number?  Do you
> look at the signature,  or do you simply evaluate the result of the
> key-extractor for each element in the unsorted list?  For example, what is
> the result of the following code?
> 
>       sort {$_.key} (1=> 'a', 10 => 'b', 2 =>'c');
> 
>    There is nothing in the signature of the key-extractor to suggest that
> all the keys are numbers, but as it turns out they all are.  Will the sort
> end up being numerical or alphabetic?

Whilst I'd very much like it to analyse the keys, detect that they're all 
numbers, and use C<< <=> >>, I suspect that if C<sort> can't determine that 
the return type of the key extractor is numeric, it will have to default to 
C<cmp>. Otherwise a case like this:

         sort {$_.key} (1=> 'a', 10 => 'b', '2' =>'c');

becomes a little too subtle.

And, after all, it isn't that much extra work to force the issue:

        sort {+$_.key} (1=> 'a', 10 => 'b', 2 =>'c');
vs:
        sort {~$_.key} (1=> 'a', 10 => 'b', 2 =>'c');

Damian



Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About