Reorder items in Erlang

I want to redefine the order of tuples looking for specific words

Example: I have a list of tuples:

[{"a",["r001"]},
 {"bi",["bidder"]},
 {"bo",["an"]}]

But sometimes the order of tuples can change, for example:

[{"bi",["bidder"]},
 {"a",["r001"]},
 {"bo",["an"]}]

or

[{"bo",["an"]},
 {"a",["r001"]},
 {"bi",["bidder"]}]

The first line / list of tuples is my unique key ("bo", "a", "bi")

But I want to be able to arrange the list of tuples, always like:

 [{"a",["r001"]},
     {"bi",["bidder"]},
     {"bo",["an"]}]

How can i achieve this?

+4
source share
2 answers

This will be done:

lists:sort(fun({A,_},{B,_}) -> A =< B end, List).

Or this, which will sort by the second element of the tuples after the first:

lists:sort(List).

I propose the second version, because without a custom sort function, it is faster for such data.

+5
source

,

lists:keysort(1, List).
+3

Source: https://habr.com/ru/post/1612139/


All Articles