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

James Toll james at jtoll.com
Tue Feb 11 15:34:31 UTC 2014


On Feb 11, 2014, at 9:08 AM, Frerich Raabe <raabe at froglogic.com> wrote:
> 
> 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]]]


Thank you for the nicely detailed explanation.  In my frustration, I was fearing I was going to have to revert to a more imperative approach to solving this, and I was hoping someone would demonstrate a more functional solution.  In the various iterations that I unsuccessfully tried, I think the major idea I was lacking was your second step, the groupBy ((==) `on` head).  That’s really the part I just wasn’t able to come up with on my own.

Again, thanks so much for the help.

Best,


James



More information about the Beginners mailing list