Sorting Classic List Threaded 4 messages Open this post in threaded view
|

Sorting

 Hi,I’m trying to sort a list of tuples. A char and a count of that char (Char , Int) e.g.[ ('r',2), ('c',2),('a', 2), ('b',3), ('f',2)]e.g. ‘r’ occurs twice etc.The order should be based on the count first and then ties broken by the natural ordering of char.So [ ('r',2), ('c',2),('a', 2), ('b',3), ('f',2)]will sort as[('b',3),('a', 2), ('c',2),('f',2), ('r',2)]I initially tried variants onsortBy (compare `on` snd)and then made a type Tup = T (Char, Int)and defined Eq and then got to the point where I felt that this had become too difficult for a simple problem and concluded that I’m missing a point somewhere and need a bit of help!Many thanksM_______________________________________________ Beginners mailing list [hidden email] http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
Open this post in threaded view
|

Re: Sorting

 On Tue, Dec 13, 2016 at 02:36:39PM +0000, mike h wrote: > Hi, > > I’m trying to sort a list of tuples. A char and a count of that char (Char , Int) > e.g. > > [ ('r',2), ('c',2),('a', 2), ('b',3), ('f',2)] > > e.g. ‘r’ occurs twice etc. > The order should be based on the count first and then ties broken by the > natural ordering of char. You should provide sortBy with an appropriate compare function, e.g.     comp (a,b) (c,d) | a > c = GT                      | -- etc etc. or go with the manky but working hack: λ> :m Data.List λ> sortOn (\(a, b) -> b*(-100) + fromEnum a) [('r',2), ('c',2),('a', 2), ('b',3), ('f',2)] [('b',3),('a',2),('c',2),('f',2),('r',2)] _______________________________________________ Beginners mailing list [hidden email] http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners