[Haskell-beginners] Sorting

Francesco Ariis fa-ml at ariis.it
Tue Dec 13 15:23:29 UTC 2016


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)]



More information about the Beginners mailing list