Question

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

Was it helpful?

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.

OTHER TIPS

The error I get (after adding some definitions to your code to get it to compile) is:

 Warning:
  Pattern match(es) are non-exhaustive
  In an equation for `genTree': Patterns not matched: _ Nil

Which tells you that you need to add a case like this:

genTree x Nil = ...

If you add the following to the top of the file (assuming youi are using GHC), it will tell you exactly where any "non-exhaustive pattern" error is-

{-# OPTIONS_GHC -Wall #-}

As the others have already mentioned, you are missing the Nil case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top