Home > DeveloperSection > Forums > How to sort tuple list in Erlang?
Ashish Pandey

Total Post:128

Posted on    March-11-2016 1:17 AM

 erlang erlang 

 1 Reply(s)
 594  View(s)
Rate this:
I am beginner in Erlang programming. I want to sort according to the second element of each tuple. I already use usort/1 and it works fine but it only works with the first element.
So I think we need to swap each elements and after we do sort operation and after swap it back.
Can you tell me any other easiest solution to sort tuple lists.

Tarun Kumar

Total Post:214

Posted on    March-14-2016 3:05 AM

If you want to sort tuples according to the second element of each tuples in a list then use keysort() function.
keysort() function is an inbuilt function in Erlang Shell which takes two parameters, in first parameter we pass the position of the element from which we want to sort and in the second parameter we pass the List. Examples are below:
1> List = [{a,b}, {c,a}, {b,c}].  // Customized List
[{a,b}, {c,a}, {b,c}]
2> L1 = lists:keysort(1, List).   // Sorting will be according to the first element of the tuples.
3> L2 = lists:keysort(2, List).   // Sorting will be according to the second element of the tuples.

Modified On Mar-14-2016 03:07:55 AM

Don't want to miss updates? Please click the below button!

Follow MindStick