Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list of pairs using sort Haskell

Tags:

haskell

I have a function (frequency) which that counts how many times each distinct value in a list occurs in that list. For example,

frequency "ababca" 

should return:

[(3, 'a'), (2, 'b'), (1, 'c')].

This works fine but now I need to sort the list using the first element within the list of the list using this function.

results   :: [Party ] -> [(Int, Party)]
results  xs = ??? frequency (sort xs) ??? 

example of desired output:

[(1, "Green"), (2, "Red"), (3, "Blue")]

The above does not work, I have no idea what I can do.

using regular 'sort'

Thank you in Advance.

like image 750
ErHunt Avatar asked Dec 21 '25 11:12

ErHunt


1 Answers

import Data.Function (on)
import Data.List (sortBy)

results xs = sortBy (compare `on` fst) (frequency xs)

-- or, if you prefer
results xs = sort (frequency xs)

Links to documentation for on, sortBy, compare, fst.

The difference is that sort sorts in ascending order of the first element of each pair, breaking tie-breaks with the second elements of the pairs, while sortBy (compare `on` fst) explicitly only looks at the first element of each pair.

like image 81
dave4420 Avatar answered Dec 24 '25 11:12

dave4420



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!