Sorting using lambda not working in Py2.1?

Alex Martelli aleaxit at yahoo.com
Fri May 4 11:47:59 CEST 2001


"Marcin 'Qrczak' Kowalczyk" <qrczak at knm.org.pl> wrote in message
news:slrn.pl.9f4d2h.nk7.qrczak at qrnik.zagroda...
> Thu, 3 May 2001 18:57:51 +0200, Alex Martelli <aleaxit at yahoo.com> pisze:
>
> > This violates the semantic constraints on sort's optional argument:
> > it must be a function that only returns 0 when arguments are to
> > be considered EQUAL for sorting purposes.  This will also return
> > 0 when x>y -- not just when they're equal.
>
> Note that using different types for
>     Booleans
>     integers
>     ordering (less, equal or greater)
> no matter if statically checked or not, would help to detect the error.

It might, depending on whether (e.g.) cmp was re-specified
to return "an ordering", while (e.g.) < is re-specified to
return "a boolean", and so on, provided, of course, that
sort was also respecified to require "an ordering" and it
checked that such a type was actually returned.  Right now,
sort does check that the comparison function returns an
int, but doesn't care whether it IS, as specified, -1 or
0 or 1 -- it treats all <0 as -1 and all >0 as 1 instead
(it uses a specific check to allow this slight "laxity"
wrt the specs).  Of course, if one IS doing anything that
is at all substantial in the comparison function, then
the type issue is the least of one's worries; the semantics
are subtler and might have been better specified in terms
of a "<" function or other strict weak ordering (as of
now, "x<y" IS all the sort algorithm ever checks, and rich
comparison use in sorting takes advantage of that).

In practice, I've found that coding the decorate/sort/
undecorate idiom is a better use of my time than looking
for subtle bugs in a comparison-function, finding out
later than I need the sort to be stable and being unable
to obtain that via comparison-function (and having to
refactor to D/S/U anyway), and invariably finding out
at profiling time that the sort-with-comparison-fun is
a bottleneck (so refactoring to D/S/U anyway)...


Alex






More information about the Python-list mailing list