How to sort tuple list in Erlang?

Total Post:128

Points:898

erlang 
 1504  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. 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 Apr-11-2018 02:11:27 AM

Answer

Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.