[Haskell-beginners] filter by max length a list of lists with equivalent values
Frerich Raabe
raabe at froglogic.com
Tue Feb 11 15:08:40 UTC 2014
On 2014-02-11 15:54, James Toll wrote:
> 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]]
> Any thoughts on how to do this would be appreciated.
After grouping the given list, so that you have
[[1,1,1,1],[2,2,2,2],[3,3],[2,2,2],[5],[6],[2,2],[7]]
Sort the list by comparing the first element of each list
ghci> sortBy (comparing head)
[[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],[2,2,2],[2,2],[3,3],[5],[6],[7]]
Then, group that again such that lists with equal elements get put into
one list:
ghci> groupBy ((==) `on` head)
[[1,1,1,1],[2,2,2,2],[2,2,2],[2,2],[3,3],[5],[6],[7]]
[[[1,1,1,1]],[[2,2,2,2],[2,2,2],[2,2]],[[3,3]],[[5]],[[6]],[[7]]]
Finally, select the "maximum" of each inner list by comparing the
length of the sub-sub-lists:
ghci> map (maximumBy (comparing length))
[[[1,1,1,1]],[[2,2,2,2],[2,2,2],[2,2]],[[3,3]],[[5]],[[6]],[[7]]]
You'll need "Data.List", "Data.Ord" and "Data.Function" for this.
--
Frerich Raabe - raabe at froglogic.com
www.froglogic.com - Multi-Platform GUI Testing
More information about the Beginners
mailing list