Haskell - 如何在排序后从元组列表中取出 n 项

Haskell - How to take n items from a tuple list after sorting

嗨,我是 haskell 的初学者。我正在尝试从此元组列表中获取前 3 个项目:

[("and",2),("cat",1),("dog",1),("rabbit",1),("the",2)]

首先,我按频率和降序对列表进行排序:

sortWords =  sortBy(flip compare `on` snd)

这给了我结果:

[("and",2),("the",2),("cat",1),("dog",1),("rabbit",1)]

然后我知道我可以执行以下功能:

take 3 [("and",2),("the",2),("cat",1),("dog",1),("rabbit",1)] 

这给了我 期望的 结果 [("and",2),("the",2),("cat",1)]

但是,我希望能够将 take 函数合并到 sortWords 函数中。问题是,当我尝试这样做时,例如:

sortWords =  take 3 (sortBy(flip compare `on` snd))

这不起作用。

理想情况下,我想保留 sortWords 作为结束函数,所以我不想将它传递给另一个函数以执行 take 函数。如果有一种方法可以在调用 sortWords 之前执行 take 这可能是一个解决方案,但是我也尝试过这个并且发现所采用的单词没有首先排序因此不会给我结果我想。

谢谢

这里的问题是 sortBy (flip compare `on` snd) 不是 元组列表,它是一个将元组列表和 returns 作为输入的函数元组列表。

我们可以使用函数组合运算符(.) :: (b -> c) -> (a -> b) -> a -> c:

sortWords :: Ord b => [(a,b)] -> [(a,b)]
sortWords = take 3 . sortBy (flip compare `on` snd)

这里我们首先将 sortBy (flip compare `on` snd) 应用于输入,然后我们将 take 3 应用于该函数的输出。