5

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?

alxndr
  • 3,851
  • 3
  • 34
  • 35
user1000622
  • 519
  • 1
  • 7
  • 18

2 Answers2

5

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.

Michael
  • 3,639
  • 14
  • 29
  • While you benchmarked your implementations you probably just wrote `lists:sort(fun({A,_},{B,_}) -> A =< B end, List)` into the shell. But it is not exactly correct. Erlang will not compile expressions entered directly into the shell but rather interpret them. So your custom function will work much slower than it should. I tried both shell written comparation function and compiled one with separate module and found that compiled function performance is OK while shell-written is indeed much slower. _So I assume your speed statement is not correct here_ – Lol4t0 Oct 21 '15 at 06:12
  • Thanks for pointing this out! I just tried it with some sample data I created, on the shell and in a module, and I couldn't achieve an order of mag difference in any comparison I must say, but the shell is a lot slower for some cases. I don't really feel it's fair to quote numbers as mileage may vary so much per data, and depending on its starting sort state, but for my case I found lists:sort/1 30% faster than lists:sort/2. I also tried lists:keysort/2 you proposed while I was at it and found that to be 19% faster than lists:sort/1. Answer ammended. – Michael Oct 21 '15 at 08:16
3

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

lists:keysort(1, List).
Lol4t0
  • 12,444
  • 4
  • 29
  • 65