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

Very interesting and technical good post!

Found a bug though: the C qsort() comparison callback needs to be able to express a being less than b by returning a negative value. The post's returns 0 if equal or 1 if greater.

My typical implementation for numerical types goes

    return a < b ? -1 : a > b;


Complete aside, one fun thing about Perl is it has an operator for this:

    a <=> b
The 'spaceship' operator. You can sort an object by its foo property, then bar property, with:

    sort { $a->foo <=> $b->foo || $a->bar <=> $b->bar } @array;
Python is still better IMO:

    sorted(array, key=lambda x: (x.foo, x.bar))


Another aside, C++ also has the spaceship operator. If you define it, the compiler generates implicit declarations for ==, <, >, etc. You can provide your own ==, too, if that would be faster, and the compiler will use that to generate !=.

There can still be reasons to define all the operations explicitly, but those are rarely encountered.

Even further aside, in discussing language features and design, the expression "but those are rare" comes up frequently. For different languages, its meaning may be radically different. In C++, it means "for that case, you have to do something a little less convenient". For almost all languages, it means "we don't handle that case, you're on your own". That depth is what has kept C++ on top of the performance and major system implementation heap for decades, not just, as is often asserted, inertia. Achieving depth takes decades.


Also possible:

    return (a > b) - (a < b);




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

Search: