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

Erlend Hamberg ehamberg at gmail.com
Tue Feb 11 16:15:28 UTC 2014


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

-- 
Erlend Hamberg
ehamberg at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20140211/1e27b245/attachment.html>


More information about the Beginners mailing list