开发者

sorting lists of lists in haskell

开发者 https://www.devze.com 2022-12-21 06:51 出处:网络
I\'m completely stumped on how to write a function that, given a list of sets returns the 开发者_Python百科sets split into sublists by size (and with the sublists ordered by the size of sets they cont

I'm completely stumped on how to write a function that, given a list of sets returns the 开发者_Python百科sets split into sublists by size (and with the sublists ordered by the size of sets they contain).

sample input

*Main> allSets
[[1,2],[8],[1,4,7,8],[5],[1,4],[1],[2,3],[1,2,5,8],[3,4,6,7],[1,2,3,4],[4],[5,6,7,8],[3,4],[3],[2,3,5,6],[7],[6],[2]]

sample output

*Main> collectByLength allSets
[[[2],[6],[7],[3],[4],[1],[5],[8]],[[3,4],[2,3],[1,4],[1,2]],[[2,3,5,6],[5,6,7,8],[1,2,3,4],[3,4,6,7],[1,2,5,8],[1,4,7,8]]]

Basically, it should group all the sets of the same size into their own set,then it groups the sets of the next largest size.


You're using the word "sets", but your code actually uses lists... So, here's a list-based solution (easily adaptable in case you'd like to switch to actual sets):

import Data.List (sortBy)
import Data.Function (on)

groupBy ((==) `on` length) $ sortBy (compare `on` length) [[0],[1,2],[3]]
-- => [[[0],[3]],[[1,2]]]


After importing Data.Function, Data.Ord and List, you can write this:

sortBy (comparing length) $ groupBy ((==) `on` length) $ sortBy (comparing length) theList
0

精彩评论

暂无评论...
验证码 换一张
取 消