An example sort that needs a comparison function
In reaction to my entry on Python 3 dropping the comparison function for sorting, some people may feel that a sorting order that is neither simple fieldbased nor based on a computed 'distance' (the two cases easily handled by a key function) is unrealistic. As it happens I can give you a great example of a sort order that cannot be handled in any other way: software package versions on Linux systems.
For simplicity (and because I know RPM best), I'm going to talk about RPMbased version numbers. RPM version numbers have three components, an epoch, a version, and a release, and ordering is based on comparing each successive component in turn. The epoch is a simple numeric comparison (higher epochs are more recent), but both the version and release can have subcomponents and each subcomponent must be compared piecewise using a relatively complex comparison for each piece (they can be all digits, letters, or mixed letters and digits). Something with extra subcomponents is more recent than something without it, so version 1.6.1 is more recent than version 1.6. A full package version can look like '1:2.4.64.fc16.cks.0'; '1:' denotes the epoch, the version is '2.4.6', and the release is '4.fc16.cks.0'.
(Most RPM packages have an epoch of '1' '0', which is
conventionally omitted when reporting package versions.)
In the presence of potential letterbased subcomponents and the complex comparison rules, you can't compare these version numbers using simple fieldbased rules, not even if you split subcomponents up into tuples and then compare a tupleoftuples (it's possible if all subcomponents are simple numbers). Nor can you compute some sort of single numerical 'distance' value for a particular version number, especially since version numbers are sort of like the rational numbers in that you can always add an essentially unlimited number of additional versions between any two apparently adjacent versions. The only real operation you have is a pure comparison, where you answer the question 'is X a higher version than Y', and this comparison requires relatively intricate code.
(Having said that, DanielMartin showed a nice way to transform things so that a keyfunction based sort can be used for a comparison function sort in comments on the earlier entry.)
Comments on this page:

