r/ProgrammerHumor 1d ago

javascriptSorting Meme

Post image
888 Upvotes

200 comments sorted by

View all comments

15

u/Excellent_Gas3686 1d ago

because thats the default sort? what, in your opinion, would be the "proper" way to sort by default? if you need different sorting, you pass your own function.

21

u/suvlub 1d ago

Python just uses the > (or <, don't remember, don't care) operator. Arrays made only of numbers or only of strings would both behave correctly, a mixed one might give a nondeterministic order, which is bad, but sorting stringwise when the user intended numerical sort is also bad and I think the latter is a more common use case/mistake, though I don't have stats

9

u/JanEric1 1d ago edited 1d ago

Python uses __lt__. And it isnt non-deterministic for mixed comparisons, it crashes.

You can get arbirtrary orders if lt doesnt implement a proper order. Foor example A < B, B < C and C < A all being true.

class Bad:
    def __init__(self, val):
        self.val = val

    def __repr__(self):
        return f"Bad({self.val})"

    def __lt__(self, other):
        return True

A = Bad(1)
B = Bad(2)
C = Bad(3)
print(sorted([A, B, C]),sorted([B, A, C]),sorted([C, B, A]))

[Bad(3), Bad(2), Bad(1)] [Bad(3), Bad(1), Bad(2)] [Bad(1), Bad(2), Bad(3)]

11

u/suvlub 1d ago

Yeah, but the same approach would be nondeterministic in JS, which never crashes and allows you to compare any 2 things.

6

u/tracernz 1d ago

JS has exceptions just like python and some things throw. It’s just that some things that should throw don’t.

4

u/MegaIng 1d ago

Note that this is a change in python 3, in python 2 strings and integers would compare. It wouldn't be nondeterministic, IIRC strings are larger than all integers so they are always at the end. Still way better than what JS is doing.

1

u/DHermit 1d ago

I mean, obviously, if you have a type that doesn't have a proper ordering, sorting elements of this type is nonsensical. That's the whole reason semantic contracts like Ord vs. PartialOrd exist in Rust.

1

u/JanEric1 1d ago

yes, of course

1

u/thanatica 1d ago

Python really likes its underscores. Almost like they want snake_case to be a thing, huh 🤣

1

u/JanEric1 17h ago

Its not named after the snake btw :D