
I am wanting to sort a list of tuples by the first and then the second item in the tuple. So [(1,2),(4,2),(2,5)] would become [(1,2),(2,5),(4,2)] I am attempting to use the Sorty function but don't seem to be having much luck tuplesort :: [(a,b)] -> [(a,b)] tuplesort [(_,_)] = sortBy (comparing fst) -- this is an attempt to organise by the first element in the tuple Any help would be much appreciated

Am Freitag 16 Oktober 2009 01:19:34 schrieb Ryan Temple:
I am wanting to sort a list of tuples by the first and then the second item in the tuple. So [(1,2),(4,2),(2,5)] would become [(1,2),(2,5),(4,2)]
That's what "sort" already does: sort [(1,2),(4,2),(2,5),(4,1)] gives [(1,2),(2,5),(4,1),(4,2)]
I am attempting to use the Sorty function but don't seem to be having much luck
tuplesort :: [(a,b)] -> [(a,b)] tuplesort [(_,_)]
That defines tuplesort on lists containing exactly one pair, probably not what you want.
= sortBy (comparing fst)
This doesn't conform to the type you gave. "sortBy (comparing fst)" has type Ord a => [(a,b)] -> [(a,b)] So your definition of tuplesort has type Ord a => [(c,d)] -> [(a,b)] -> [(a,b)] which doesn't look like the type of a sorting function.
-- this is an attempt to organise by the first element in the tuple
You would achieve that by tuplesort = sortBy (comparing fst) or, eta-expanded, tuplesort xs = sortBy (comparing fst) xs But if you finally want to sort by the second component also (subordinate to sorting by the first component), it's much easier to go the whole way at once and use plain "sort".
Any help would be much appreciated

On Fri, Oct 16, 2009 at 8:07 AM, Daniel Fischer
You would achieve that by
tuplesort = sortBy (comparing fst)
or, eta-expanded,
tuplesort xs = sortBy (comparing fst) xs
But if you finally want to sort by the second component also (subordinate to sorting by the first component), it's much easier to go the whole way at once and use plain "sort".
For completeness sake, you can do it like that : tuplesort = sortBy (comparing fst `mplus` comparing snd) It's interesting to know how to do it if you want to sort using a different function than the compare of Ord. The "mplus" use some instances of Monoid that you'll find in Data.Monoid so don't forget to import it. -- Jedaï

On Fri, Oct 16, 2009 at 10:37 AM, Chaddaï Fouché
On Fri, Oct 16, 2009 at 8:07 AM, Daniel Fischer
wrote: You would achieve that by
tuplesort = sortBy (comparing fst)
or, eta-expanded,
tuplesort xs = sortBy (comparing fst) xs
But if you finally want to sort by the second component also (subordinate to sorting by the first component), it's much easier to go the whole way at once and use plain "sort".
tuplesort = sortBy (comparing fst `mplus` comparing snd)
Ooops, that's "mappend" rather than "mplus" :
tuplesort = sortBy (comparing fst `mappend` comparing snd)
(it would be really cool if (++) was a synonym for mappend though as it used to be) -- Jedaï
participants (3)
-
Chaddaï Fouché
-
Daniel Fischer
-
Ryan Temple