How can it be done in most simply way to write (or maybe there is something embedded in haskell) function which takse as arguments list of tuples (String, Int) and Int x and return top x tuples as list according to x value.
I wonder if its possible to write a function which also takes 3 argument which is the name of (or index) of filed in tuple according to which sorting has to be done.
What are best solutions to make it quite generic?
take xtakes the first x items from the sorted list.sortBysorts the list given as second argument using the sorting function given as the first argument.(compare `on` fst)compares the first values of each tuple.Note that this example compares the first value of each tuple for sorting. To sort by the second value, replace
fstwithsnd.You see that the
sortByfunction is very generic, as it lets you define the function used to compare the values. The function takes two arguments and should return one of LT, EQ or GT. Note that the functioncomparerequires both arguments to derive fromOrd. The helper functiononcan be found in the moduleData.Function. The functionsortByis in the moduleData.List.EDIT:
Here is a complete working example that sorts a list of tuples by comparing their first values and prints the first 2 tuples of the resulting list. Note that I replaced the
onfrom the example above with a equivalent function that shows whatondoes internally.EDIT:
As Tom Lokhorst pointed out in his comment, the function
comparingfrom the moduleData.Ordis a more readable replacement/shortcut foron compare, so the above could also be written assortBy (comparing fst).