1

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.

1
  • 3
    Use: ghc -Wall prog.hs and ghc should tell you the pattern(s) which are not accounted for. Commented Aug 4, 2016 at 7:06

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Or maybe it was meant to be longer [] _ = False ?
I'm leaving that for the OP. :)
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.