Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder elements in Erlang

Tags:

erlang

I want to redefine the order of a tuple looking for specific words

Example, I have a list of tuples like this:

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

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

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

or

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

The first string/list of the tuple is my unique key ("bo","a","bi")

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

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

How can I achieve this?

like image 228
user1000622 Avatar asked Oct 18 '15 16:10

user1000622


People also ask

What is the difference between ordsets and ordsets in Erlang?

One difference is that while this module considers two elements as different if they do not match ( =:= ), ordsets considers two elements as different if and only if they do not compare equal ( == ). Erlang/OTP 24.0 introduced a new internal representation for sets which is more performant.

Are there any valid Erlang expressions?

In this section, all valid Erlang expressions are listed. When writing Erlang programs, it is also allowed to use macro- and record expressions. However, these expressions are expanded during compilation and are in that sense not true Erlang expressions. Macro- and record expressions are covered in separate sections:

What's new in Erlang/OTP 24?

Erlang/OTP 24.0 introduced a new internal representation for sets which is more performant. Developers can use this new representation by passing the {version, 2} flag to new/1 and from_list/2, such as sets:new ( [ {version, 2}]). This new representation will become the default in future Erlang/OTP versions.

What are variables in Erlang/OTP?

Starting from Erlang/OTP R15, Module, Name, and Arity can also be variables. A fun defined in this way refers to the function Name with arity Arity in the latest version of module Module. A fun defined in this way is not dependent on the code for the module in which it is defined. More examples are provided in Programming Examples.


2 Answers

This will do it:

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

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

lists:sort(List).

I offer the second version, because without the custom sort function, it is faster for data like this.

like image 69
Michael Avatar answered Oct 07 '22 13:10

Michael


If you need to sort by specified element, you just sort by specified element

lists:keysort(1, List).
like image 29
Lol4t0 Avatar answered Oct 07 '22 14:10

Lol4t0