[Haskell-beginners] filter by max length a list of lists with equivalent values

James Toll james at jtoll.com
Tue Feb 11 16:43:39 UTC 2014


On Feb 11, 2014, at 10:15 AM, Erlend Hamberg  wrote:

> Another way to do this would be to sort the sub lists according to what they contain (the list heads) and then their length (to resolve ties).
> You could then use nubBy with “(==) `on` head” to remove lists and only be left with the longest lists. Since nub[By] keeps only the first occurrence of each element when there are duplicates, “comparing length” is flipped – meaning that longer lists come first. This gives us the following function: 
> 
>     nubBy ((==) `on` head) . sortBy (comparing head <> flip (comparing length)) . group
> 
> Where (<>) is from Data.Monoid. An explanation of using monoids to build sorting combinators can be found in this reddit post [note that the author uses (++) for (<>)]:
> http://www.reddit.com/r/programming/comments/7cf4r/monoids_in_my_programming_language/c06adnx


Thank you for this example and the link.  I have not explored the Data.Monoid module yet, but I will read through the reddit post.

Best,


James


More information about the Beginners mailing list