Let’s say I have the following type
type Key = String
type Score = Int
data Thing = Thing Key Score
And if I have an array of them like this:
[Thing "a" 7, Thing "b" 5, Thing "a" 10]
Is there a standard way to reduce this so that I don’t have any duplicate keys? If two keys match, I want to take the better score
[Thing "b" 5, Thing "a" 10]
Basically first we must decide what is problem solving and what is implementation difficulties. So what If we first sort by
Score, and then just keep the first occurrences in the sorted list with respect toKey? That should work, let’s look at the haskell implementation:Now we try run this in
ghci:Checkout hoogle if you are uncertain about the functions I used in the solution. It indeed takes some time to learn how to use
onand those functions.