Reputation: 3894
I get non exhaustive patterns exception for the following code
--determine which list is longer
longer::[a]->[a]->Bool
longer [] [] = False
longer _ [] = True
longer (_:[]) (_:[]) = False
longer (_:xs) (_:ys) = longer xs ys
I don't understand what I am doing wrong here.
Upvotes: 1
Views: 13325
Reputation: 530920
You need 4 cases, but you don't need to treat two singleton lists as a separate case.
longer :: [a] -> [a] -> Bool
-- 1) Two empty lists
longer [] [] = False
-- 2) An non-empty list and an empty list
longer _ [] = True
-- 3) An empty list and a non-empty list
longer [] _ = ???
-- 4) Two non-empty lists
longer (_:xs) (_:ys) = longer xs ys
Actually, you only need 3 cases in the proper order, depending on what longer [] _
is supposed to be.
-- First case: if longer [] _ is suppose to be True
longer :: [a] -> [a] -> Bool
longer [] [] = True
longer (_:xs) (_:ys) = longer xs ys
-- We get this far if one is empty and the other is not,
-- but we don't care which one is which.
longer _ _ = False
-- Second case: if longer [] _ is supposed to be False
longer :: [a] -> [a] -> Bool
longer (_:xs) (_:ys) = longer xs ys
longer _ [] = True
longer [] _ = False -- This covers longer [] [] as well.
Upvotes: 2
Reputation: 48644
You are not handling this case:
longer [] _ = undefined
The pattern (_:[])
assumes that you have a minimum of one element in the list. In your code, you are missing the case when the first list is empty and the second list may not be empty.
Upvotes: 5