1

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!

1 Answer 1

3

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)]]
1
  • And that's why the on function exists! Handy, huh? Dec 20, 2012 at 21:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.