HOW TO SORT TUPLE LIST IN ERLANG?

Ashish Pandey

Total Post:128

Points:898
Posted by  Ashish Pandey
erlang 
 666  View(s)
Ratings:
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.
Thankyou.
  1. Tarun Kumar

    Post:214

    Points:1642
    Re: How to sort tuple list in Erlang?

    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.
    [{a,b},{b,c},{c,a}]
    3> L2 = lists:keysort(2, List).   // Sorting will be according to the second element of the tuples.
    [{c,a},{a,b},{b,c}]

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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!