您可以排序sortBy :: (a -> a -> Ordering) -> [a] -> [a] https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-List.html#v:sortBy:
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] https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-List.html#v:sortOn:
import Data.List(sortOn)
import Data.Ord(comparing)
import Data.Tuple(swap)
orderSwap :: (Ord a, Ord b) => [(a, b)] -> [(a, b)]
orderSwap = sortOn 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