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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With