通过比较双倍的总和来排序

时间:2015-01-18 15:42:15

标签: list haskell

maxSumPair :: [(Int,Int)] -> (Int,Int)
maxSumPair l = head $ sortBy (comparing auxSum) l

auxSum :: (Int,Int) -> Int
auxSum (a,b) = a+b

使用函数maxSumPair并且我想计算哪个双打有最大的总和。

例如,这是它应该如何工作:

> maxSumPairs [(1,10),(6,6),(10,1)] 
(6,6)

但是我的功能给了我(1,10)而不是(6,6)。我的错是什么?

2 个答案:

答案 0 :(得分:6)

默认情况下,

sortBy按升序执行稳定排序 。因此,head将获得最小的一对。相反,您可以调整auxSum以返回负和值,以按降序对实际数据进行排序并得到头部,如下所示

auxSum :: (Int,Int) -> Int
auxSum (a,b) = -(a + b)

> maxSumPair [(1,10),(6,6),(10,1)] 
(6,6)

如果您不想更改auxSum,请使用last功能代替head,就像这样

auxSum :: (Int,Int) -> Int
auxSum (a,b) = a + b

maxSumPair :: [(Int,Int)] -> (Int,Int)
maxSumPair l = last $ sortBy (comparing auxSum) l

> maxSumPair [(1,10),(6,6),(10,1)] 
(6,6)

注意:或者,您可以使用maximumBy函数,这对于这种情况非常有效(因为sortBy将在O(n * log n)时间内运行但是maximumBy会在O(n)中完成它,就像这样

auxSum :: (Int,Int) -> Int
auxSum (a,b) = a + b

> maximumBy (comparing auxSum) [(1,10),(6,6),(10,1)] 
(6,6)

答案 1 :(得分:2)

只是添加到讨论中,请注意您可以通过翻转比较函数来执行反向排序:

reverseSort xs = sortBy (flip compare) xs
reverseSortBy cmp xs = sortBy (flip cmp) xs

所以你可以写:

maxSumPair xs = head $ sortBy (flip $ comparing auxSum) xs