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

James Toll james at jtoll.com
Tue Feb 11 14:54:53 UTC 2014


Hi,

I have what’s proving to be a tricky little problem for me to solve.  I’m trying to take a list of a list of Int’s and return the longest list for each list with elements of equivalent value.  That’s not a great explanation, so let me try to give an example:

If I have a list of lists grouped by element value.

ghci> group [1,1,1,1,2,2,2,2,3,3,2,2,2,5,6,2,2,7]  
[[1,1,1,1],[2,2,2,2],[3,3],[2,2,2],[5],[6],[2,2],[7]]  

I would like to take the subset of the outer list containing only the longest of the inner lists for any particular element.

So for this particular example, the desired output would be:

[[1,1,1,1],[2,2,2,2],[3,3],[5],[6],[7]]  

The lists [2,2,2] and [2,2] would be removed because they’re shorter than [2,2,2,2].

Any thoughts on how to do this would be appreciated.

Thanks and best regards,


James


More information about the Beginners mailing list