[erlang-questions] map elements in defined order

Ulf Wiger ulf@REDACTED
Thu Oct 26 17:30:23 CEST 2017

Looking at the maps API, I see no function that can present the contents of
a map in the defined order.

Because there IS a defined order, described in the Erlang Reference Manual:

«Maps are ordered by size, two maps with the same size are compared by keys
in ascending term order and then by values in key order. In maps key order
integers types are considered less than floats types.»

Note that the key ordering described above doesn't follow normal Erlang
term ordering, so lists:sort(maps:to_list(Map)) will produce something will
a well-defined order, but comparing the sorted lists of two maps is not
guaranteed to have the same outcome as comparing the maps themselves.

I can solve this by using lists:sort/2, but this seems contrived.

To clarify, e.g. msgpack:pack(Map) will perform a maps:to_list(Map). This
is not guaranteed to produce the same result across Erlang versions, since
maps:to_list/1 says pairs "are returned in arbitrary order".

Yet there is no alternative API function that will return pairs in the
defined sort order, although presumably there is an efficient internal
implementation for producing it.

Wouldn't it be reasonable to have such a function?

Ulf W
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20171026/2a87cbc5/attachment.htm>

More information about the erlang-questions mailing list