views:

183

answers:

2

i'm completely stumped on how to Write a function that, given a list of sets returns the 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

+6  A: 

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]]]
Michał Marczyk
+2  A: 

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

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