import Control.Arrow ((>>>), (&&&), second) import GHC.Exts (sortWith) lfsort :: [[a]] -> [[a]] lfsort = zip [1..] >>> map (second (length &&& id)) >>> sortWith (snd>>>fst) >>> cntDupLength undefined [] >>> sortWith (snd>>>fst) >>> sortWith fst >>> map (\(_,(_,(_,a))) -> a) where cntDupLength :: Int -> [(Int,(Int,a))] -> [(Int,(Int,a))] -> [(Int,(Int,(Int,a)))] cntDupLength _ lls [] = map ((,) (length lls)) $ reverse lls cntDupLength _ [] (x@(_,(l,_)):xs) = cntDupLength l [x] xs cntDupLength l lls ys@(x@(_,(l1,_)):xs) | l == l1 = cntDupLength l (x:lls) xs | otherwise = (map ((,) (length lls)) $ reverse lls) ++ cntDupLength undefined [] ys