对元组列表进行排序的函数 - Haskell [英] Function to sort a list of tuples - Haskell

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

问题描述



我试着编写一个函数order来排序一个列表由另一个函数频率产生的元组(频率计数列表a中的不同元素的数目给出一个这样的结果,例如频率aabbbccc)将产生结果,[(2,a),(3,b) ,(3,c)])按升序排列。



如果我在前奏中编写>排序(频率分数),它会对它进行排序(分数是成绩列表,即[a,b,c,c]。

但是当我尝试写一个函数..

  results :: [a]  - > [(Int,a)] 
results = sort(频率分数)

可悲的是,这种说法不适用于太多的参数。



对不起,明显的问题,并提前感谢。

解决方案

你忘了让你的函数接受一个参数。 / p>

 结果:: [a]  - > [(Int,a)] 
结果分数= )

没有它,编译器会看到您的类型签名并推断为了返回类型 [a] - > [(Int,a)] sort 必须接受另一个参数, 。

但是,接下来的问题是我那么你不能对任意组件类型的元组进行排序。请参阅@ luqui关于如何处理该问题的答案。


Sorry for the easy question it's just I'm extremely new to haskell..

I'm trying to write a function "order" which will sort a list of tuples produced by another function "frequency" (frequency counts the number of distinct elements in a list a gives one such result, say > frequency "aabbbccc", would incur the result, [(2,a),(3,b),(3,c)]) into ascending order. I can't work out how to write it.

If I write >sort (frequency score) into the prelude it will sort it (score being a list of grades, i.e ["a", "b", "c", "c"].

But when I try to write a function..

results :: [a] -> [(Int, a)]
results = sort (frequency score)

It sadly does not work saying that sort is applied to too many arguments.

Sorry for the obvious question and thanks in advance.

解决方案

You forgot to make your function take an argument.

results :: [a] -> [(Int, a)]
results score = sort (frequency score)

Without it, the compiler sees your type signature and infers that in order to return something of type [a] -> [(Int, a)], sort must take another argument, which it doesn't.

However, the next problem is then that you can't sort a list of tuples with arbitrary component types. See @luqui's answer for how to deal with that.

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

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