Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort array of tuples by 2nd element then by first element in Haskell

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[("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

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading