如何在不声明新数据的情况下更改类型为(String,Int)的元组的Ord实例? [英] How to change Ord instance for tuple of type (String, Int) without declaring a new data?

查看:66
本文介绍了如何在不声明新数据的情况下更改类型为(String,Int)的元组的Ord实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to sort a list of type [(String, Int)]. By default, it is sorting by Strings and then Ints (if the Strings are equal). I want it to be the opposite — first, compare Ints and then if equal compare the Strings. Additionally, I don't want to switch to [(Int, String)].

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

I found a way to do so by defining an instance, but it only works for my own data type, which I don't want to use.

推荐答案

您可以使用 sortOn :: Ord b =>(a-> b)->[a]->[a] :

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

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

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

Or we can just perform two swaps and sort the intermediate result:

import Data.Tuple(swap)

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

这当然不是标准订购".如果您要定义的固有顺序不同于已定义实例派生的固有顺序,则应定义自己的类型.

This is of course not the "standard ordering". If you want to define an inherent order differently than one that is derived by the instances already defined, you should define your own type.

例如:

newtype MyType = MyType (String, Int) deriving Eq

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

这篇关于如何在不声明新数据的情况下更改类型为(String,Int)的元组的Ord实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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