Problem 28.b
Sort a list according to the frequency of the sublist length. Place lists with rare lengths first, those with more frequent lengths come later. If the frequency of two or more sublists are equal the any order is acceptable.
Example
(List.map List.length
<| sortByLengthFrequency
[[1],[2],[3],[6,7,8],[2,34,5],[]])
== [0, 3, 3, 1, 1, 1]
Unit Test
import Html
import List
sortByLengthFrequency : List (List a) -> List (List a)
sortByLengthFrequency xs =
-- your implementation goes here
[]
main : Html.Html a
main =
Html.text
<| case test of
0 ->
"Your implementation passed all tests."
1 ->
"Your implementation failed one test."
x ->
"Your implementation failed " ++ (toString x) ++ " tests."
test : Int
test =
List.length
<| List.filter ((==) False)
[ (List.map List.length
<| sortByLengthFrequency [ [ 1 ], [ 2 ], [ 3 ], [ 6, 7, 8 ], [ 2, 34, 5 ], [] ]
)
== [ 0, 3, 3, 1, 1, 1 ]
, (List.map List.length
<| sortByLengthFrequency [ [ 1 ], [ 2 ], [ 3 ], [ 6 ], [ 2 ], (List.range 1 10) ]
)
== [ 100000, 1, 1, 1, 1, 1 ]
, (List.map List.length
<| sortByLengthFrequency [ [ 1, 2, 3 ], [ 6, 7, 8 ], [ 0 ], [ 2, 3, 5 ] ]
)
== [ 1, 3, 3, 3 ]
, (List.map List.length
<| sortByLengthFrequency [ [] ]
)
== [ 0 ]
]
(..) : Int -> Int -> List Int
(..) start end =
List.range start end
Hints
- First find the frequency for each list length, then use that to sort. You may need to partially apply the length/frequency data to the comparison function you pass to
List.sortBy
. - The module List.extra (link), not available on http://elm-lang.org/try, provides a groupBy function. If you group by length, you could then sort the groups and flatten again.