Repository navigation
Conversation
| %% sort by key | ||
| lists:keysort(3, People) | ||
| ≡ lists:sort(fun(A, B) -> maps:is_ordered(age, A, B) end, People) |
There was a problem hiding this comment.
The name and meaning of maps:is_ordered(age, A, B) is slightly awkward.
An alternative idea is to add another sort function:
lists:sortby(fun(M) -> maps:get(age, M) end, People)There was a problem hiding this comment.
The sort is a family of functions, so that would require a new lists:usortby(), lists:mergeby() and lists:rmergeby() as well.
There was a problem hiding this comment.
Right, and usortby. Good point. So it's probably not a good idea.
But lists:keysort/2 is also a one-off. We don't have keyusort, keymergeby, keyrmergeby, etc. nor with a fun for reverse order, etc.
lists:keysort(3, People) is readable as its own abstraction, but I don't know if maps:is_ordered(age, A, B) is any more reader-friendly than the explicit maps:get(age, A) =< maps:get(age, B).
There was a problem hiding this comment.
Thats why I added the comment on is_ordered above, on the other hand people miss the = in '=<' so bugs happen because of that so a general ordering function would be good.
is_le/3 ? Short but le is more of a C-programmer convention.
There was a problem hiding this comment.
Another option is to introduce a compare contract, that returns eq, lt, gt. Of course, that introduces another problem in that you need to have new sorting functions anyway, but it would provide a more general foundation, because you can add maps:compare(Key1, Key2, Map). Elixir uses it as a general contract for comparing datetimes, decimals, etc. This functionality can also be useful for records and any other data structure where you cannot simply assume the ordering of the fields is sufficient.
Add more generic lists functions to provide alternatives to
lists:key*for any terms.Also provide predicate helpers
maps:has/3andmaps:is_ordered/3so users don't have to write funs for themevery time.
Name is_ordered/3 may need other name suggestions.