Reputation: 664256
I have a list of lists of tuples ([[(Int, Custom)]]
) and I would like to sort the outer lists by comparing the integers with each other. It should behave just like a normal two-dimensional sort, i.e. it should sort the first by the first list items, then by the second items and so on - but compare the first parts instead of the whole tuples.
For a one-dimensional list I would've used sortBy (comparing fst)
, but I'm totally lost with having them wrapped in another list. I know it would work automatically if I'd make my Custom
an instance of Ord
as the sort worked automatically then, but it is not really orderable.
Please comment if you'd like to have an example and expected result. Thanks in advance!
Upvotes: 1
Views: 395
Reputation: 664256
Uh, right after asking the question it hit me like a stroke:
comparing
needs a function that returns an orderable result, not an Ordering or the sorted partial list [(Int, Custom)]
(which is unorderable):
comparing :: Ord a => (b -> a) -> b -> b -> Ordering
comparing = on compare
So what I had to return is a list of the orderable integers, i.e. just map fst
. Altogether:
sortBy (compare `on` map fst)
:: Ord a => [[(a, b)]] -> [[(a, b)]]
Upvotes: 3