Saturday, 4 June 2016

Haskell: Sort list of lists based on the length of sub lists

By using sortBy function defined in Data.List module, we can solve this problem easily.


sortByLength.hs
import Data.List

{-Compare two elements based on length -}
compareElements :: [a] -> [a] -> Ordering
compareElements list1 list2 = compare (length list1) (length list2)

{- Sort elements by length -}
sortByLength :: [[a]] -> [[a]]
sortByLength [] = []
sortByLength (xs) = sortBy compareElements xs

*Main> :load sortByLength.hs
[1 of 1] Compiling Main             ( sortByLength.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> sortByLength ["Hi", "Hello", "a", "bcd", "as"]
["a","Hi","as","bcd","Hello"]
*Main> 
*Main> sortByLength [[1, 2, 3], [2, 3], [3, 5, 7, 9, 11], [1], [1, 2]]
[[1],[2,3],[1,2],[1,2,3],[3,5,7,9,11]]
*Main> 
*Main> sortByLength []
[]
*Main> 
*Main> sortByLength ["abcd"]
["abcd"]


Previous                                                 Next                                                 Home

No comments:

Post a Comment