Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Technically they are equivalent, meaning that theoretically you can implement one with the other. The main advantage of sorting with [-1,0,1] is if you are sorting by multiple parameters

Convoluted example: sort some cars by year then by weight except with all Toyota first

In general it is easy to simulate multiple SQL `order by` clauses with [-1,0,1].

Using primitives you can map each car to something like "0t-1994y-0300kg" (remembering to left pad numbers) and sort by that.

In practice they are equivalent (when used correctly) but it is easier to implement primitive sorting with [-1,0,1] than viceversa.

Sometimes I wish languages would have native equality and order operators on (immutable) arrays, so that [1,1]<[1,2]<[2,0]<[2,0,-1] would work...



They are not "technically equivalent", as I've shown above. You can implemnt papre/scissors/rock with [-1,0,1], which is not linear ordering function.

And you didn't show anything for which ordering cannot be defined by mapping objects (with any number of parameters) to strings, which is kind of the whole purpose of sortBy anyway.


> And you didn't show anything for which ordering cannot be defined by mapping objects (with any number of parameters) to strings, which is kind of the whole purpose of sortBy anyway

I did so by intentionally, as i believe that mapping to complex enough strings is enough.

> You can implemnt papre/scissors/rock with [-1,0,1], which is not linear ordering function.

In PHP and in most other languages NaN == NaN, NaN === NaN, NaN <= NaN, and NaN < NaN are all false due to how IEEE floating point numbers are defined so you can have weird stuff going on there too.

With some testing:

$v=[1,2,3,4,5,6]; usort($v,$f);

for:

$f=function($a,$b){ return ($a - $b)%3; }; $f=function($a,$b){ return -($a - $b)%3; }; $f=function($a,$b){ return 1; }; $f=function($a,$b){ return -1; }; $f=function($a,$b){ return 0; };

it appears that once $f($a,$b) is calculated $f($b,$a) is inferred to be -$f($a,$b) and to guarantee $f($v[i],$v[i+1]) <= 0 under that assumption.

But I am not sure... honestly i don't care... I am not arguing that one is better than the other...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: