haskell sorting

ぃ、小莉子 提交于 2021-02-07 12:11:17

问题


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?


回答1:


take x $ sortBy (compare `on` fst) [("asd", 1), ...]

take x takes the first x items from the sorted list. sortBy sorts 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 fst with snd.

You see that the sortBy function 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 function compare requires both arguments to derive from Ord. The helper function on can be found in the module Data.Function. The function sortBy is in the module Data.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 on from the example above with a equivalent function that shows what on does internally.

import Data.Function
import Data.List

main = print $ mySort [("foo", 1), ("bar", 2), ("baz", 3), ("quux", 4)] 2

mySort list x = take x $ sortBy (\ x y -> compare (fst x) (fst y)) list

EDIT: As Tom Lokhorst pointed out in his comment, the function comparing from the module Data.Ord is a more readable replacement/shortcut for on compare, so the above could also be written as sortBy (comparing fst).



来源:https://stackoverflow.com/questions/2788195/haskell-sorting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!