问题
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.
回答1:
You can sort with 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 (comparing swap)
or with 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.
For example with:
newtype MyType = MyType (String, Int) deriving Eq
instance Ord MyType where
compare (MyType a) (MyType b) = comparing swap a b
回答2:
The newtype
is the usual way to define a new instance for an existing type.
Although you will still need to have a constructor for a newtype type there is no computational overhead. The compiler will remove the newtype wrapper opposed to defining a type with data
.
来源:https://stackoverflow.com/questions/57417687/how-to-change-ord-instance-for-tuple-of-type-string-int-without-declaring-a-n