Haskell error: “non-exhaustive patterns”

佐手、 提交于 2019-12-10 21:18:56

问题


So i have this function and when i try to use it like this: mergeSortedLists [1,1] [1,1] it gives me an error:

[1,1*** Exception: SortFunctions.hs:(86,1)-(91,89): Non-exhaustive patterns in function mergeSortedLists

85 mergeSortedLists :: (Ord t)       => [t] -> [t] -> [t]
86 mergeSortedLists [] []            = []
87 mergeSortedLists (x:[]) []        = x:[]
88 mergeSortedLists [] (y:[])        = y:[] 
89 mergeSortedLists (x:[]) (y:[])    = (max x y) : (min x y) : []
90 mergeSortedLists (x:tail1) (y:tail2) | x > y  = x : (mergeSortedLists tail1     (y:tail2))
91                                      | otherwise = y : (mergeSortedLists (x:tail1) tail2)

I can't figure out the source of a problem since i think i covered every case possible. What could be the problem here?


回答1:


Your patterns for the second and third cases cover lists of length 1 merged with an empty list, but nothing covers longer lists merged with the empty list. That is, you didn't cover cases like this:

mergeSortedLists [3, 2, 1] []
mergeSortedLists [] [3, 2, 1]

Here's a function that does what I think you are trying to do in fewer cases:

mergeSortedLists :: (Ord t) => [t] -> [t] -> [t]
mergeSortedLists x [] = x
mergeSortedLists [] y = y
mergeSortedLists (x:tail1) (y:tail2)
    | x > y     = x : (mergeSortedLists tail1 (y:tail2))
    | otherwise = y : (mergeSortedLists (x:tail1) tail2)

(Also, isn't your function technically merging reverse sorted lists?)



来源:https://stackoverflow.com/questions/11615031/haskell-error-non-exhaustive-patterns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!