I’m trying to write a function that accepts a list of comparators and returns a comparator that will compare a pair of values using the first comparator, then the second one if the first comparator returned EQ etc.
What I came up with was the following function:
import Data.Monoid
chainCompare :: [a -> a -> Ordering] -> a -> a -> Ordering
chainCompare = mconcat . map ($)
EDIT: chainCompare can also be written as (thanks to Vitus for pointing it out):
chaincompare = mconcat
An example of using this function is the following:
import Data.List
import Data.Ord
sortBy (chainCompare [comparing length, comparing sum]) [[1..100], [1..20], [100..200]]
However, this function requires using comparing explicitly, so I tried to modify the function like this:
chainCompare :: Ord b => [a -> b] -> a -> a -> Ordering
chainCompare = mconcat . map (comparing $)
However, chainCompare will cause a compile error in this case (Also, even if this example did compile, it would not work for empty strings):
sortBy (chainCompare [length, head]) [['a'..'z'], ['A'..'Z'], "Lorem ipsum dolor sit amet"]
Is it possible to make chainCompare polymorphic in the sense that b can be any type of instance Ord? I have seen some Haskell code using the forall extensions and tried searching for them, but I still cannot figure out what each specific extension is useful for.
chainCompare [f, g]will always cause an error iffandgare functions with different types – no matter how you definechainCompare. You can even remove thechainCompareand just write[f, g]and it will still cause an error. The reason for that is that it is simply not possible to have values of different types in a list.Sometimes when you want to store values of different types in the same list it can make sense to use existential types (a GHC extension). With that you could define an existential type
Comparatorand use the list[Comparator length, Comparator head]. However that has no benefit over usingcomparinglike you did in your first example, so it would be quite pointless in this case.So your first code using
comparingis really the best you can do.For the record, here’s how the code would look like using existential types:
The only difference in usage over your first version is that you have to write
Comparatorinstead ofcomparingand that it’s not possible to use a comparison function that does not compare based on a key. So as I said, it doesn’t really add any benefit over your first version.