# 99 questions/Solutions/28

### From HaskellWiki

< 99 questions | Solutions(Difference between revisions)

(another solution without 'comparing') |
|||

Line 8: | Line 8: | ||

import List | import List | ||

import Data.Ord (comparing) | import Data.Ord (comparing) | ||

− | lsort :: [[a]]->[[a]] | + | |

+ | lsort :: [[a]] -> [[a]] | ||

lsort = sortBy (comparing length) | lsort = sortBy (comparing length) | ||

</haskell> | </haskell> | ||

− | This function also works for empty list. Import List to use sortBy. | + | This function also works for empty list. Import <hask>List</hask> to use <hask>sortBy</hask>. |

+ | |||

+ | If you wanted to solve it without the <hask>comparing</hask> function, you could do: | ||

+ | |||

+ | <haskell> | ||

+ | import List | ||

+ | |||

+ | lsort :: [[a]] -> [[a]] | ||

+ | lsort = sortBy (\xs ys -> compare (length xs) (length ys)) | ||

+ | </haskell> | ||

b) Again, we suppose that a list contains elements that are lists themselves. But this time the objective is to sort the elements of this list according to their <b>length frequency</b>; i.e., in the default, where sorting is done ascendingly, lists with rare lengths are placed first, others with a more frequent length come later. | b) Again, we suppose that a list contains elements that are lists themselves. But this time the objective is to sort the elements of this list according to their <b>length frequency</b>; i.e., in the default, where sorting is done ascendingly, lists with rare lengths are placed first, others with a more frequent length come later. | ||

Solution: TODO | Solution: TODO |

## Revision as of 16:53, 17 July 2010

Sorting a list of lists according to length of sublists

a) We suppose that a list contains elements that are lists themselves. The objective is to sort the elements of this list according to their length. E.g. short lists first, longer lists later, or vice versa.

Solution:

import List import Data.Ord (comparing) lsort :: [[a]] -> [[a]] lsort = sortBy (comparing length)

List

sortBy

comparing

import List lsort :: [[a]] -> [[a]] lsort = sortBy (\xs ys -> compare (length xs) (length ys))

b) Again, we suppose that a list contains elements that are lists themselves. But this time the objective is to sort the elements of this list according to their **length frequency**; i.e., in the default, where sorting is done ascendingly, lists with rare lengths are placed first, others with a more frequent length come later.

Solution: TODO