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"]
Tags: bonsai, code, Haskell, hett, kata, length, lists, praxis, programming, sort
September 4, 2011 at 6:26 pm |
Very elegant, but, your byLengthFreq is not a stable sort: “ijkl” should stay before “o”!