Sort a list of tuples by 2nd tuple element

13,930

Solution 1

Most of the sorting problems could be solved with sortBy ::(a -> a -> Ordering) -> [a] -> [a] function. So the task is to generate ordering function which compares two elements based on length of second element of the tuple. compare `on` (length . snd) :: (a1, [a]) -> (a1, [a]) -> Ordering is what we actually need.

eblo> sortBy (compare `on` (length . snd)) [("x", [1,2,3]), ("y", [1,2]), ("z", [1,2,3,4])]
[("y",[1,2]),("x",[1,2,3]),("z",[1,2,3,4])]

Solution 2

sortBy (comparing $ length . snd) [("x", [1,2,3]), ("y", [1,2]), ("z", [1,2,3,4])]
Share:
13,930
user1226239
Author by

user1226239

Updated on June 04, 2022

Comments

  • user1226239
    user1226239 almost 2 years

    Possible Duplicate:
    Sort a list of tuples by their second elements

    Hey there i have a list of tuples that looks like this

    [("x", [1,2,3]), ("y", [1,2]), ("z", [1,2,3,4])]
    

    i want to sort the list in increasing order according to the length of the integer list which is the 2nd element in the tuple, however my haskell is poor at best and i cannot figure out a way to do this.