[erlang-questions] map elements in defined order

Michael Truog mjtruog@REDACTED
Thu Oct 26 21:43:39 CEST 2017


On 10/26/2017 12:13 PM, Ulf Wiger wrote:
> But again, Jesper, just about everyone relies on the fact that maps follow the general principle that there is a well-defined term comparison order. Otherwise, maps would be highly unsuitable to use in keys, and generally treacherous to use as a replacement for records. Following the Principle of Least Surprise, it's a darned good thing that Erlang doesn't randomize the key order in its maps.
>
> I doubt that anyone would abuse an extra function that produces the map element pairs in the internally defined sort order, given that the documentation would clearly state that it's more expensive than maps:to_list/1 (though likely faster than lists:sort(maps:to_list(M), fun custom_sort_fun/2) - not to mention less error-prone.)
>
> But it's not a feature I'm willing to go to war over. If no one else sees a use for it, I'm willing to concede that it has low priority. :)
>

At a low-level, a hash array mapped trie is unordered because it relies on a hash function, so using the Erlang map in an ordered way might be possible but would be inefficient.  If you need an ordered mapping, I think my Erlang trie is a better option at https://github.com/okeuday/trie , though it requires Erlang string keys (binary keys are supported by the btrie module, but that is slow).  That doesn't necessarily help msgpack source code though, unless it would be a separate output option that was added.

Best Regards,
Michael



More information about the erlang-questions mailing list