KeithFrost
Why are tuples ordered differently than lists in elixir/erlang?
Enum.sort([[3, -999], [3], [2, 999]])
# => [[2, 999], [3], [3, -999]]
Enum.sort([{3, -999}, {3}, {2, 999}])
# => [{3}, {2, 999}, {3, -999}]
I ask because it came up when I was storing directed graph edges in :gb_sets as {node1, node2}, and I couldn’t just collect all the edges from a node starting with
:gb_sets.iterator_from({node1}, set)
I had to write
:gb_sets.iterator_from({node1, @min_value}, set)
instead.
Marked As Solved
josevalim
Tuples and maps can get their size computed in constant time, so it is cheap to use that for sorting, that’s not the case for lists! And the sooner you can tell two elements are different, for example by checking their size, the faster sorting will be.
Also Liked
NobbZ
I can not tell you why the decission was made like this, but:
Lists are compared element by element. Tuples are ordered by size, two tuples with the same size are compared element by element.
Emphasizis mine.
rvirding
If you are not going to sort tuples by size how would you order the 2 tuples {x,39,d,z} and {x,39,d}? Yes, you can compare the elements but what do you do when one tuple “runs out” of elements? Does the smaller tuple then come first, that is no element is always smaller than any element? Or what?
The current method is simple and consistent.
garrison
But if the tuples are the same size, the comparison is O(n) anyway. Is this not the common case? How often are you sorting tuples of different sizes? If anything short-circuiting is less predictable.
Like, with respect, because the list of people I’m disagreeing with here is pretty ridiculous, I find this argument kinda specious.
By this logic why not compare binaries by size first? You know why: it would be confusing and annoying. And with tuples it is also confusing and annoying, for the same reasons.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








