Haskell排序 [英] haskell sorting

查看:48
本文介绍了Haskell排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以最简单的方式编写(或者在haskell中嵌入某些内容)函数,该函数将takse作为元组(String,Int)和Int x的参数列表,并根据x返回顶部x个元组作为列表值.

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.

我想知道是否有可能编写一个函数,该函数也接受3个参数,该参数是必须根据其进行排序的元组中文件名(或索引)的名称.

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 x $ sortBy (compare `on` fst) [("asd", 1), ...]

take x 从排序列表中获取前x个项目. sortBy 使用作为第一个参数给出的排序功能对作为第二个参数给出的列表进行排序.(compare`on` fst)比较每个元组的第一个值.请注意,此示例比较每个元组的第一个值以进行排序.要按第二个值排序,请将 fst 替换为 snd .

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.

您会看到 sortBy 函数非常通用,因为它使您可以定义用于比较值的函数.该函数有两个参数,应返回LT,EQ或GT中的一个.请注意,函数 compare 要求两个参数都从 Ord 派生.辅助功能 on 可以在模块 Data.Function 中找到.函数 sortBy 位于模块 Data.List 中.

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.

这是一个完整的工作示例,该示例通过比较元组的第一个值对一个元组列表进行排序,并打印结果列表的前两个元组.请注意,我用等效的函数替换了上面示例中的 on ,该函数可以显示 on 在内部的作用.

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

正如汤姆·洛霍斯特(Tom Lokhorst)在评论中指出的那样,模块 Data.Ord 中的功能 comparing 是比较中 on 的更易读的替换/快捷方式,因此上面的代码也可以写为 sortBy(与fst相比).

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).

这篇关于Haskell排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆