Search code examples
haskellpattern-matchingguard

Why do non-exhaustive guards cause irrefutable pattern match to fail?


I have this function in Haskell:

test :: (Eq a) => a -> a -> Maybe a
test a b
  | a == b = Just a
test _ _ = Nothing

This is what I got when I tried the function with different inputs:

ghci>test 3 4
Nothing
ghci>test 3 3
Just 3

According to Real World Haskell, the first pattern is irrefutable. But it seems like test 3 4 doesn't fails the first pattern, and matches the second. I expected some kind of error -- maybe 'non-exhaustive guards'. So what is really going on here, and is there a way to enable compiler warnings in case this accidentally happens?


Solution

  • The first pattern is indeed an "irrefutable pattern", however this does not mean that it will always choose the corresponding right hand side of your function. It is still subject to the guard which may fail as it does in your example.

    To ensure all cases are covered, it is common to use otherwise to have a final guard which will always succeed.

    test :: (Eq a) => a -> a -> Maybe a
    test a b
      | a == b    = Just a
      | otherwise = Nothing
    

    Note that there is nothing magic about otherwise. It is defined in the Prelude as otherwise = True. However, it is idiomatic to use otherwise for the final case.

    Having a compiler warn about non-exaustive guards would be impossible in the general case, as it would involve solving the halting problem, however there exist tools like Catch which attempt to do a better job than the compiler at determining whether all cases are covered or not in the common case.