Home > Software design >  Sort array of tuples by 2nd element then by first element in Haskell
Sort array of tuples by 2nd element then by first element in Haskell

Time:11-13

I am trying to sort this array of tuples by the 2nd element but if the elements being compared are equal, I want to sort them based off the 1st element. I've done research but can only find to sort by 1st element or by 2nd element only, instead of checking both

this is what I have so far:

sortTupleSndFirst :: (Ord a, Ord b) => [(a,b)] -> [(a,b)]
sortTupleSndFirst = sortBy(flip compare `on` snd)
people = [("Hal", 20), ("Susann", 31),("Dwight", 19), ("Kassandra", 21), ("Lawrence", 25), ("Cindy", 22), ("Cory", 27), ("Mac", 19), ("Romana", 27), ("Doretha", 32), ("Danna", 20), ("Zara", 23), ("Rosalyn", 26), ("Risa", 24), ("Benny", 28), ("Juan", 33), ("Natalie", 25)]

main:: IO ()

main = 
  do
     print(sortTupleSndFirst people)

My output is:

[("Juan",33),("Doretha",32),("Susann",31),("Benny",28),("Cory",27),("Romana",27),("Rosalyn",26),("Lawrence",25),("Natalie",25),("Risa",24),("Zara",23),("Cindy",22),("Kassandra",21),("Hal",20),("Danna",20),("Dwight",19),("Mac",19)]

but I need Hal and Danna to be switched since they have the same number but their names need to be alphabetized

CodePudding user response:

You can make a function that maps (x, y) on (Down y, x) so that it first on the second item in descending order, and then by the first item:

import Data.List(sortOn)
import Data.Ord(Down(Down))

sortTupleSndFirst = sortOn (\(x, y) -> (Down y, x))
  • Related