Posts Tagged ‘lists’

Programming Praxis – Hett’s Problem 1.28

August 9, 2011

In today’s Programming Praxis, our goal is to sort a list of lists by length and by length frequency. Let’s get started, shall we?

A quick import:

import qualified Data.List.Key as K

Sorting by length is trivial.

byLength :: [[a]] -> [[a]]
byLength = K.sort length

Sorting by frequency of the list lengths is a bit more complicated since we need to group and ungroup the lists, but still a one-liner.

byLengthFreq :: [[a]] -> [[a]]
byLengthFreq = concat . byLength . K.group length . byLength

Some tests to see if everything is working properly:

main :: IO ()
main = do print $ byLength ["abc","de","fgh","de","ijkl","mn","o"]
                        == ["o","de","de","mn","abc","fgh","ijkl"]
          print $ byLengthFreq ["abc","de","fgh","de","ijkl","mn","o"] 
                            == ["o","ijkl","abc","fgh","de","de","mn"]