gpt4 book ai didi

sorting - 如何在不声明新数据的情况下更改类型(String,Int)元组的 Ord 实例?

转载 作者:行者123 更新时间:2023-12-02 12:50:08 24 4
gpt4 key购买 nike

我正在尝试对 [(String, Int)] 类型的列表进行排序。默认情况下,它按字符串排序,然后按整数排序(如果字符串相等)。我希望它是相反的——首先比较整数,然后如果相等则比较字符串。另外,我不想切换到[(Int, String)] .

我找到了一种通过定义实例来实现此目的的方法,但它仅适用于我自己的数据类型,我不想使用它。

最佳答案

您可以使用 sortBy :: (a -> a -> Ordering) -> [a] -> [a] 进行排序:

import Data.List(sortBy)
import Data.Ord(comparing)
import Data.Tuple(swap)

orderSwap :: (Ord a, Ord b) => [(a, b)] -> [(a, b)]
orderSwap = sortBy (<b>comparing swap</b>)

或使用 sortOn :: Ord b => (a -> b) -> [a] -> [a] :

import Data.List(<b>sortOn</b>)
import Data.Ord(comparing)
import Data.Tuple(swap)

orderSwap :: (Ord a, Ord b) => [(a, b)] -> [(a, b)]
orderSwap = <b>sortOn</b> swap

或者我们可以只执行两次交换并对中间结果进行排序:

import Data.Tuple(swap)

orderSwap :: (Ord a, Ord b) => [(a, b)] -> [(a, b)]
orderSwap = map swap . sort . map swap

这当然不是“标准顺序”。如果您想要定义一种与已定义的实例派生的顺序不同的固有顺序,则应该定义您自己的类型。

例如:

newtype MyType = MyType (String, Int) deriving Eq

instance Ord MyType where
compare (MyType a) (MyType b) = comparing swap a b

关于sorting - 如何在不声明新数据的情况下更改类型(String,Int)元组的 Ord 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57417687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com