When I compile the following code with GHC (using the -Wall
flag):
module Main where
data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show)
insert :: (Ord a) => a -> Tree a -> Tree a
insert x EmptyTree = Node x EmptyTree EmptyTree
insert x (Node a left right)
| x == a = Node a left right
| x < a = Node a (insert x left) right
| x > a = Node a left (insert x right)
main :: IO()
main = do
let nums = [1..10]::[Int]
print . foldr insert EmptyTree $ nums
GHC complains that pattern matching in insert
is non-exhaustive:
test.hs|6| 1:
|| Warning: Pattern match(es) are non-exhaustive
|| In an equation for `insert': Patterns not matched: _ (Node _ _ _)
Why is GHC issuing this warning? It is pretty obvious that the pattern GHC complains about is handled in insert x (Node a left right)
.
GHC is not able to infer whether your three guards in the
insert x (Node a left right)
cover all possible cases, and consequently there will be no body to be associated withinsert x (Node a left right)
. Try replacing the last conditionx > a
withotherwise
(a synonim forTrue
). In this specific case however, it's true that the guards do not cover all cases, see augustss' example about double numbers.Riccardo is correct, GHC doesn't infer that your guards can't possibly all be false. So accept his answer please.
I'm going to digress and talk about coding style.
Your motivation for not using
otherwise
may have been that it looks unsightly:Looking at this code, a human reader must confirm to themselves that the final guard accepts precisely those cases where
x > a
.We could instead write it like this:
The
Ordering
type returned bycompare
has only the three valuesEQ
,LT
, andGT
, so GHC can confirm that you've covered all possibilities, and a human reader can easily see that you've covered them correctly.This is also more efficient code: we call
compare
once, instead of calling==
and then probably calling<
as well.Now I'm going to digress some more and talk about laziness.
You've probably also written a function similar to this:
When
x == a
, you need to know that the tree uses theNode
constructor, and that its first argument is equal tox
. You don't need to know what either of the subtrees are.But now look back at my definition of
insert
above. When the tree it's given is aNode
, it always returns aNode
whose first argument is alwaysa
. But it doesn't state that up front: instead it evaluatesx `compare` a
.We can rewrite
insert
to perform the comparison as late as possible:Now we return the
Node a
bit as soon as possible --- even if the comparison throws an error! --- and we still perform the comparison once at most.It's because the pattern matching is incomplete. There's no guarantee that one of
x==a
,x<a
, orx>a
holds. For instance, if the type isDouble
andx
is NaN then none of them areTrue
.