Search code examples
haskellinsertbinary-treeliterate-programmingnon-exhaustive-patterns

Non-exhaustive pattern in function-Haskell


I've written a function, that Inserts an Element into a binary Tree, but every time I try to run it, I get the a non-exhaustive pattern in function.

type Eintrag = (Person, Anschrift, SozNr)

data Tree = Nil | Node Eintrag Tree Tree deriving (Eq, Show)

singleton :: Eintrag -> Tree
singleton x = Node x Nil Nil

genTree :: Eintrag -> Tree-> Tree
genTree x (Node e l r)= if ((Node e l r)==Nil)
    then (singleton  x)
    else if (soznr x) < (soznr e )
            then (Node e (genTree x l) r)
            else if (soznr x) > (soznr  e )
                    then (Node e l (genTree x r))
                    else (Node e l r)

Could you please give me some hints? Thanks


Solution

  • You haven't included a definition for what happens when the tree you are inserting into is Nil, which presumably looks like

    genTree x Nil = singleton x
    

    You tried to do this with the line

    genTree x (Node e l r) = if (Node e l r == Nil)
        then singleton x
        else ...
    

    but if you think about it, you'll see that cannot work. The pattern match ensures that the tree you are looking at is of the form Node _ _ _, and so it is never Nil. That is, the test in your if expression always evaluates to False.