简体   繁体   中英

Sorting lists in list by length using bubble sort - Haskell

I have an input, which is of type [[a]] and I am trying to sort the lists in the list by their length. I am working on my own implementation of bubble sort, which currently looks like this:

myInput :: Ord a => [[a]] -> [[a]]
myInput [[]] = [[]]
myInput [[x]] = [[x]]
myInput (x : xs) = mySort x (myInput xs)

mySort :: Ord a => [a] -> [[a]] -> [[a]]
mySort x [[]] = [x]
mySort x (y:ys) | (length x) < (length y) = x:y:ys
                | otherwise = y:(myInput x ys)

However, when I input myInput[[1,2],[1]] , I get a non-exhaustive pattern error:

[[1]*** Exception: CourseworkRev.hs:(197,1)-(200,49): Non-exhaustive patterns in function myInput

I am probably doing something wrong when declaring the empty lists, as this is a recursion error (correct me if I am wrong). Any tips on how to make this working? Thanks!

myInput has no pattern for an empty list, only for a list with one element that is an empty list. You likely do not need patterns like [[]] and [[x]] anyway, since for a list with a single element, you will return a list with that element, regardless of it length, so:

myInput :: Ord a => [[a]] -> [[a]]
myInput  = 
myInput  = 
myInput (x : xs) = mySort x (myInput xs)

[[x]] matches with a list that contains exactly one sublist [x] which is a list with one element. So this will match with [[1]] , but not with [[1,2]] . [x] on the other hand matches with any singleton list: a list with one element so [[1]] , [[1,4]] , [[1,4,2,5]] , and [[]] will all match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM