use*_*228 4 sorting haskell list
这里有一个如何使用自定义排序对列表进行排序的示例:http: //zvon.org/other/haskell/Outputlist/sortBy_f.html
xxx a b | odd a = LT
| otherwise = GT
Input: sortBy xxx [1,2,3,4,5,6,7]
Output: [1,3,5,7,6,4,2]
Run Code Online (Sandbox Code Playgroud)
标准小于订单让我比较列表,例如
[1,2,3] < [0,4,5]
Run Code Online (Sandbox Code Playgroud)
是假的.但这不适用于上面的示例函数:
Main> xxx [1,2,6] [1,7,3]
ERROR - Cannot infer instance
*** Instance : Integral [a]
*** Expression : xxx [1,2,6] [1,7,3]
Run Code Online (Sandbox Code Playgroud)
有没有简单的方法将这样的订单扩展到列表?
我想要这个功能的原因是使用sortBy使用我的自定义排序对列表列表进行排序.
我要感谢示例解决方案代码,有关阅读内容的建议或介于两者之间的任何内容.我希望有一些内置的方法可以用语言来完成这个,而不是编写一个直接比较列表的函数.
您可以使用代码将比较函数转换为列表的比较函数:
import Data.Monoid (mconcat)
compareList :: (a -> b -> Ordering) -> [a] -> [b] -> Ordering
compareList _ [] [] = EQ
compareList _ (_:_) [] = GT
compareList _ [] (_:_) = LT
compareList comparer (x:xs) (y:ys) =
comparer x y `mappend` compareList comparer xs ys
Run Code Online (Sandbox Code Playgroud)
现在您可以使用xxx两个列表:
> compareList xxx [1,2,6] [1,7,3]
LT
> compareList xxx [2,2,6] [1,7,3]
GT
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用它来使用比较器对嵌套列表进行排序:
> sortBy (compareList xxx) [[2,2,6], [1,7,3], [1,1,1]]
[[1,7,3],[1,1,1],[2,2,6]]
Run Code Online (Sandbox Code Playgroud)