Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change Ord instance for tuple of type (String, Int) without declaring a new data?

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.

like image 562
Bildo Avatar asked Aug 08 '19 17:08

Bildo


1 Answers

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
like image 159
Willem Van Onsem Avatar answered Nov 09 '22 17:11

Willem Van Onsem